import React, { useEffect, useState, useMemo } from 'react';
import { Accordion, ScrollArea, Card, Group, Text, Avatar, LoadingOverlay, Box, TextInput, Badge, Button } from '@mantine/core';
import { IconSearch, IconRefresh } from '@tabler/icons-react';
import UsersAvatarGroup from "../../ui/UsersAvatarGroup";
import { useSelector, useDispatch } from 'react-redux';
import { fetchAllCompanies } from "../../Settings/store/companySlice";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { translate } from '../../../utils/i18n';
import { clearLoadedSections } from '../../Settings/store/taskSlice';


const WorkspaceLists = ({ onClose }) => {

    const dispatch = useDispatch();
    const location = useLocation();
    const navigate = useNavigate()
    const { loggedInUser, xWpNonce } = useSelector((state) => state.auth.session);
    const { companies, isError } = useSelector((state) => state.settings.company);
    const { projectInfo } = useSelector((state) => state.settings.task);

    const [isLoading, setIsLoading] = useState(true);
    const [search, setSearch] = useState('');

    const fetchData = async () => {
        setIsLoading(true);
        try {
            await dispatch(fetchAllCompanies());
        } catch (error) {
            console.log(error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        if (!xWpNonce) return;
        fetchData();
    }, [dispatch, xWpNonce]);

    const id = useParams().id;

    const goToTasksList = (id) => {
        // Only clear sections if switching to a different project
        if (Number(projectInfo?.id) !== Number(id)) {
            dispatch(clearLoadedSections());
        }
        navigate(`/project/task/list/${id}`)
        onClose();
    }

    // Get user's project role from JWT project_roles
    const getUserProjectRole = (projectId) => {
        const projectRoles = loggedInUser?.project_roles || [];
        const match = projectRoles.find(pr => String(pr.project_id) === String(projectId));
        return match?.name || null;
    };

    // Filter companies by search + hide workspaces with no active projects
    const filteredCompanies = useMemo(() => {
        if (!companies || companies.length === 0) return [];
        const q = search.toLowerCase().trim();

        return companies
            .map(company => {
                const activeProjects = (company.projects || []).filter(p => String(p.status) === '1');
                if (activeProjects.length === 0) return null;

                if (!q) return { ...company, _filteredProjects: activeProjects };

                // Filter: match workspace name OR any project name
                const wsMatch = company.name?.toLowerCase().includes(q);
                const matchingProjects = activeProjects.filter(p => p.name?.toLowerCase().includes(q));

                if (wsMatch) return { ...company, _filteredProjects: activeProjects };
                if (matchingProjects.length > 0) return { ...company, _filteredProjects: matchingProjects };
                return null;
            })
            .filter(Boolean);
    }, [companies, search]);

    return (
        <>
            {/* Search */}
            <Box px={4} pb={8}>
                <TextInput
                    size="xs"
                    placeholder="Search workspaces or projects..."
                    leftSection={<IconSearch size={14} />}
                    value={search}
                    onChange={(e) => setSearch(e.currentTarget.value)}
                />
            </Box>

            <Box style={{ position: 'relative' }}>
                <LoadingOverlay visible={isLoading} overlayBlur={2} />

                {/* Error state */}
                {!isLoading && isError && (
                    <Box ta="center" py={30}>
                        <Text size="sm" c="dimmed" mb={8}>Failed to load workspaces.</Text>
                        <Button variant="light" color="teal" size="xs" leftSection={<IconRefresh size={14} />} onClick={fetchData}>
                            Retry
                        </Button>
                    </Box>
                )}

                {!isLoading && !isError && (
                <ScrollArea scrollbarSize={4} offsetScrollbars={true}
                    className={`w-full pr-1 ${appLocalizer?.is_admin ? 'h-[calc(100vh-170px)]' : 'h-[calc(100vh-170px)]'}`}
                >

                    {filteredCompanies.length > 0 ? (
                        <Accordion variant="separated" defaultValue={filteredCompanies.find(company =>
                            company._filteredProjects?.some(project =>
                                location && (
                                    location.pathname === `/project/task/list/${project.id}` ||
                                    location.pathname === `/project/task/board/${project.id}` ||
                                    location.pathname === `/project/task/calendar/${project.id}`
                                )
                            )
                        )?.id?.toString() || ''} classNames={{
                            label: '!py-3 !font-semibold !text-sm',
                            item: '!mt-2 !border-solid !border !border-gray-300',
                            control: '!bg-white font-bold !rounded-md',
                        }}>
                            {filteredCompanies.map((item) => (
                                <Accordion.Item key={item.id} value={item.id.toString()}>
                                    <Accordion.Control chevron={item._filteredProjects.length === 0 && <span />}>
                                        <Text size="md" weight={900}>{item.name}</Text>
                                        <Group position="apart">
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8" fill="none">
                                                    <circle cx="4" cy="4" r="4" fill="#F1975A" />
                                                </svg>
                                                <Text size="xs">{translate('%d users engaged').replace('%d', item.members && item.members.length)}</Text>
                                            </div>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8" fill="none">
                                                    <circle cx="4" cy="4" r="4" fill="#39758D" />
                                                </svg>
                                                <Text size="xs">{translate('%d project').replace('%d', item._filteredProjects.length)}</Text>
                                            </div>
                                        </Group>
                                    </Accordion.Control>
                                    {item._filteredProjects.length > 0 &&
                                        <Accordion.Panel>
                                            {item._filteredProjects.map((project, index) => {
                                                const roleName = getUserProjectRole(project.id);
                                                return (
                                                    <Card key={`${project.id}-${index}`} className='mb-2 mt-0' shadow="sm" radius="sm"
                                                        withBorder style={{ borderColor: '#39758d', cursor: 'pointer', backgroundColor: location && (location.pathname === '/project/task/list/' + project.id || location.pathname === '/project/task/board/' + project.id || location.pathname === '/project/task/calendar/' + project.id) ? '#F5F9FB' : 'white' }}
                                                        onClick={() => goToTasksList(project.id)}>
                                                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '-7px' }}>
                                                            <Text size="sm" weight={700} style={{ flex: 1 }}>{project.name}</Text>
                                                            {roleName && (
                                                                <Badge size="xs" variant="light" color="teal" radius="xl" mr={4}>{roleName}</Badge>
                                                            )}
                                                            <UsersAvatarGroup users={project.members} size={30} maxCount={2} />
                                                        </div>
                                                        <Group position="apart">
                                                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>
                                                                <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8" fill="none">
                                                                    <circle cx="4" cy="4" r="4" fill="#F1975A" />
                                                                </svg>
                                                                <Text size="xs">{translate('%d users engaged').replace('%d', project.members && project.members.length)}</Text>
                                                            </div>
                                                            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                                <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8" fill="none">
                                                                    <circle cx="4" cy="4" r="4" fill="#39758D" />
                                                                </svg>
                                                                <Text size="xs">{translate('%d task').replace('%d', project.total_tasks && project.total_tasks)}</Text>
                                                            </div>
                                                        </Group>
                                                    </Card>
                                                );
                                            })}
                                        </Accordion.Panel>
                                    }
                                </Accordion.Item>
                            ))}
                        </Accordion>
                    ) : (
                        <Text size="sm" ta="center" py={20} c="dimmed">
                            {search ? translate('No workspaces or projects match your search.') : translate('You haven\'t been assigned to a specific workspace or project yet.')}
                        </Text>
                    )}
                </ScrollArea>
                )}

            </Box>

        </>
    );
};

export default WorkspaceLists;
