import React, { useState, useEffect } from 'react';
import {
    Modal,
    Button,
    Text,
    Group,
    Avatar,
    Table,
    Box,
    Stack,
    Badge,
    Divider,
    ActionIcon,
    Select,
    Grid,
    Anchor,
} from '@mantine/core';
import { IconCheck, IconAlertTriangle, IconBrandWhatsapp } from '@tabler/icons-react';
import { useNavigate } from 'react-router-dom';
import { translate } from "../utils/i18n";
import { hasPermission } from './ui/permissions';
import { useDispatch, useSelector } from 'react-redux';
import { changeMemberProjectRole } from './Settings/store/projectSlice';
import { showNotification } from '@mantine/notifications';
import { updateRoleAssignmentModalStatus } from './Settings/store/settingSlice';

export const SuperAdminRoleAssignmentModal = () => {
    const navigate = useNavigate();
    const { assignedSuperAdmins } = useSelector((state) => state.settings.setting);
    const [opened, setOpened] = useState(false);

    const { roles } = useSelector((state) => state.auth.role);
    // State for select/tick per user+project
    const [memberRoles, setMemberRoles] = useState({});
    const [successUserProjectKeys, setSuccessUserProjectKeys] = useState([]);

    const dispatch = useDispatch();
    const { loggedUserId } = useSelector((state) => state.auth.user);
    const { loggedInUser, xWpNonce } = useSelector((state) => state.auth.session);

    useEffect(() => {
        const timeout = setTimeout(async () => {
            // Open modal if there are assigned super admins without proper roles
            if (xWpNonce && assignedSuperAdmins && assignedSuperAdmins.length > 0) {
                try {
                    const result = await dispatch(
                        updateRoleAssignmentModalStatus(
                            loggedInUser ? loggedInUser.loggedUserId : loggedUserId
                        )
                    ).unwrap();

                    if (result?.already_shown === false) {
                        setOpened(true);
                    }
                } catch (error) {
                    console.error('Role assignment modal check failed:', error);
                }
            }
        }, 1000);

        return () => clearTimeout(timeout);
    }, [assignedSuperAdmins, loggedInUser, xWpNonce]);

    useEffect(() => {
        if (opened) {
            window.isRoleAssignmentModalOpen = true;
        } else {
            if (window.isRoleAssignmentModalOpen) {
                window.isRoleAssignmentModalOpen = false;
                // Dispatch event so others can listen
                window.dispatchEvent(new Event('roleAssignmentModalClosed'));
            }
        }
    }, [opened]);

    const handleRoleChange = (user, roleId, projectId) => {
        if (!roleId) {
            showNotification({
                title: 'Role Required',
                message: 'Please select a role for the user.',
                color: 'red',
                autoClose: 3000,
            });
            return;
        }
        // Key by user.user_id+project
        setMemberRoles(prev => ({
            ...prev,
            [`${user.user_id}_${projectId}`]: roleId
        }));
        const memberWithRole = {
            ...user,
            id: user.user_id,
            role_id: roleId,
            project_id: projectId
        };
        dispatch(changeMemberProjectRole({
            id: projectId,
            data: {
                member: memberWithRole,
                updated_by: loggedUserId
            }
        })).then((response) => {
            if (response.payload && response.payload.status === 200) {
                setSuccessUserProjectKeys(prev => [
                    ...prev,
                    `${user.user_id}_${projectId}`
                ]);
                showNotification({
                    title: 'Success',
                    message: response?.payload?.message || 'Role assigned successfully',
                    color: 'green',
                    autoClose: 2000,
                });
            } else {
                showNotification({
                    title: 'Error',
                    message: response?.payload?.message || 'Failed to assign role',
                    color: 'red',
                    autoClose: 3000,
                });
            }
        });
    };
    // Deduplicate assignedSuperAdmins by user_id and project_id
    const dedupedSuperAdmins = Array.from(
        new Map(
            assignedSuperAdmins.map(item => [`${item.user_id}_${item.project_id}`, item])
        ).values()
    );
    // Group by project_id for robust grouping
    const groupedByProject = dedupedSuperAdmins.reduce((acc, item) => {
        if (!acc[item.project_id]) {
            acc[item.project_id] = { project: item.project, users: [] };
        }
        acc[item.project_id].users.push(item);
        return acc;
    }, {});

    const onClose = () => {
        setOpened(false);
    };

    const handleGoToSettings = () => {
        onClose();
    };

    // Build table rows: each project with its users
    // Table rows: group by project_id, alternate background for each project group
    const tableRows = Object.entries(groupedByProject).map(([projectId, { project, users }], projectIdx) => {
        return users.map((user, index) => (
            <Table.Tr key={`${projectId}-${user.user_id}-${index}`} style={{ background: projectIdx % 2 === 0 ? '#fafafa' : '#fff' }}>
                {index === 0 && (
                    <Table.Td rowSpan={users.length} ta="start" style={{ width: '220px', minWidth: '220px' }}>
                        {project}
                    </Table.Td>
                )}
                <Table.Td>
                    <Grid col={12} align="center" gutter={0} grow>
                        <Grid.Col span={6} >
                            <Group gap="sm">
                                <Avatar 
                                    src={user.avatar}
                                    name={user.username} 
                                    radius="xl" 
                                    size={32}
                                    color="blue"
                                />
                                <Stack gap={2}>
                                    <Text fw={500} size="sm">
                                        {user.username}
                                    </Text>
                                    <Text size="xs" c="dimmed">
                                        {user.email}
                                    </Text>
                                </Stack>
                            </Group>
                        </Grid.Col>
                        <Grid.Col span={1} ta={'end'}>
                            {successUserProjectKeys.includes(`${user.user_id}_${user.project_id}`) && (
                                    <ActionIcon size={'sm'} variant="filled" radius="xl" aria-label="Settings" color="#11790d">
                                        <IconCheck style={{ width: '70%', height: '70%' }} stroke={1.5}  />
                                    </ActionIcon>
                                )}
                        </Grid.Col>
                        <Grid.Col span={5} >
                            <Group justify='center' align='center'>
                                <div className="flex justify-end"
                                    onClick={(e) => e.stopPropagation()}
                                    onMouseDown={(e) => e.stopPropagation()}
                                >
                                    <Select
                                        placeholder={translate("Select Role")}
                                        searchable
                                        allowDeselect={false}
                                        size="md"
                                        className="min-w-[100px] w-full"
                                        data={
                                            roles?.length
                                                ? roles
                                                    .filter((role) => role.slug !== "superadmin")
                                                    .map((role) => ({
                                                        value: role.id.toString(),
                                                        label: role.name,
                                                    }))
                                                : []
                                        }
                                        value={memberRoles[`${user.user_id}_${user.project_id}`]}
                                        onChange={(v) => handleRoleChange(user, v, user.project_id)}
                                    />
                                </div>
                            </Group>
                        </Grid.Col>
                    </Grid>
                </Table.Td>
            </Table.Tr>
        ));
    }).flat();

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={
                <Group spacing="sm">
                    <ActionIcon size={'md'} variant="filled" radius="xl" aria-label="Settings" color="#ff0f0f">
                        <IconAlertTriangle style={{ width: '70%', height: '70%' }} stroke={1.5}  />
                    </ActionIcon>
                    
                    <Text fw={600} size="lg">
                        {translate('Update Project Roles')}
                    </Text>
                </Group>
            }
            centered
            size="70rem"
            radius="md"
            withCloseButton={true}
        >
            <Divider mb="xs" />
            <Stack gap="4">
                <Text size="sm" c="dimmed">{translate('Dear Admin,')}</Text>

                <Text size="sm" c="dimmed">
                    {translate('We’ve introduced a more flexible and robust access control system in LazyTasks. You can now assign users different roles for each project, instead of a single global role.')}
                </Text>

                <Text size="sm" c="dimmed">
                    {translate('As part of this update, all users have been automatically assigned their existing global role across all projects. However, a few users couldn’t be updated due to role conflicts. Please review the list and assign them appropriate roles to keep access control smooth and secure.')}
                </Text>

                <Text size="sm" c="dimmed">
                    {translate('If you have any questions or need clarification, feel free to reach out — I’m happy to help!')}
                </Text>

                <Text size="sm" c="dimmed">{translate('Kind regards,')}</Text>
                <Text size="sm" c="dimmed">{translate('Noor Khan')}</Text>
                <Text size="sm" c="dimmed">{translate('Founder, LazyCoders LLC')}</Text>

                <Text size="sm" c="dimmed">
                    <Group gap="4">
                        <Anchor href="mailto:nmkhan@lazycoders.co" target="_blank" rel="noreferrer">
                        nmkhan@lazycoders.co
                        </Anchor>
                        {' | '}
                        <Anchor href="https://wa.me/16478484547" target="_blank" rel="noreferrer">
                            <Group gap="4" justify="center" wrap="nowrap" >
                                <IconBrandWhatsapp size={14} />
                                <span>Chat on WhatsApp</span>
                            </Group>
                        </Anchor>
                    </Group>
                </Text>

                <Box
                    style={{
                        overflowX: 'auto',
                        border: '1px solid #E0E0E0',
                        borderRadius: '8px',
                    }}
                >
                    <Table.ScrollContainer h={300}>
                    <Table striped highlightOnHover horizontalSpacing="sm" verticalSpacing="md">
                        <Table.Thead>
                            <Table.Tr>
                                <Table.Th fw={600}>
                                    {translate('Project Name')}
                                </Table.Th>
                                <Table.Th fw={600}>
                                    {translate('User Name')}
                                </Table.Th>
                            </Table.Tr>
                        </Table.Thead>
                        <Table.Tbody>
                            {tableRows}
                        </Table.Tbody>
                    </Table>
                    </Table.ScrollContainer>
                </Box>

                <Button
                    fullWidth
                    color="#11790d"
                    size="md"
                    fw={500}
                    onClick={handleGoToSettings}
                    disabled={Object.keys(memberRoles).length === 0}
                >
                    {translate('Done')}
                </Button>
            </Stack>
        </Modal>
    );
};