import { useEffect, useState } from 'react';
import {
    Box,
    Card, Group,
    ScrollArea,
    Select,
    Text, Paper,
    ThemeIcon,
} from '@mantine/core';
import { useSelector } from 'react-redux';
import { BarChart } from "@mantine/charts";
import { __ } from "@wordpress/i18n";
import { IconSelector, IconChartBar } from '@tabler/icons-react';
import ProjectSummery from './ProjectSummery';
import { useElementSize } from '@mantine/hooks';

const DashboardBarChart = ({ dragHandle }) => {
    const { userProjects, allProjects } = useSelector((state) => state.settings.myTask);
    const { loggedUserId } = useSelector((state) => state.auth.user);
    const { loggedInUser } = useSelector((state) => state.auth.session);
    const { ref, width, height } = useElementSize();

    const userId = loggedInUser?.loggedUserId ?? loggedUserId;
    const isAdmin = loggedInUser?.is_superadmin || loggedInUser?.llc_roles?.some(role => role.slug === 'admin');
    const isWpAdmin = loggedInUser?.roles?.includes('administrator');

    const [view, setView] = useState('chart');
    const [userProjectShort, setUserProjectShort] = useState([]);
    const [allProjectShort, setAllProjectShort] = useState([]);

    useEffect(() => {
        const shortened = allProjects.map(arr => {
            if (arr.name.toString().length > 4) {
                return { ...arr, nameShortened: arr.name.toString().substring(0, 4) + '...' }
            }
            return arr;
        })
        setAllProjectShort(shortened);

    }, [allProjects]);

    useEffect(() => {
        const shortened = userProjects.map(arr => {
            if (arr.name.toString().length > 4) {
                return { ...arr, nameShortened: arr.name.toString().substring(0, 4) + '...' }
            }
            return arr;
        })
        setUserProjectShort(shortened);
    }, [userProjects]);

    function ChartTooltip({ label, payload }) {
        if (!payload) return null;

        return (
            <Paper px="md" py="sm" withBorder shadow="md" radius="md">
                <Text fw={500} mb={5}>
                    {payload[0]?.payload?.name}
                </Text>
                {payload.map(item => (
                    <Text key={item.name} c={item.color} fz="sm">
                        {item.name}: {item.value}
                    </Text>
                ))}
            </Paper>
        );
    }

    return (
        <Card padding="md" withBorder radius="md" h="100%" ref={ref}>
            <Card.Section withBorder inheritPadding py="xs" className="bg-[#EBF1F4] mb-2">
                <Box className={dragHandle ? "draggable-header cursor-grab" : ""}>
                    <Group justify="space-between" align="center" wrap="nowrap">
                        <Group gap="xs" wrap="nowrap">
                            {dragHandle}
                            <ThemeIcon size="sm" radius="sm" variant="light" color="#39758D">
                                <IconChartBar size={14} />
                            </ThemeIcon>
                            <Text fw={600} size="sm">{__( 'Project Summary', 'lazytasks-project-task-management' )}</Text>
                        </Group>
                        <Box
                            onMouseDown={(e) => { if (dragHandle) e.stopPropagation(); }}
                            style={{ background: '#fff', borderRadius: 6, paddingLeft: 8 }}
                        >
                            <Select
                                size="xs"
                                variant="unstyled"
                                placeholder={__( 'Select View', 'lazytasks-project-task-management' )}
                                data={[
                                    { value: 'chart', label: __( 'Chart', 'lazytasks-project-task-management' ) },
                                    { value: 'list', label: __( 'List', 'lazytasks-project-task-management' ) }
                                ]}
                                value={view}
                                onChange={setView}
                                allowDeselect={false}
                                comboboxProps={{ width: 120, position: 'bottom-start' }}
                                rightSection={<IconSelector size={14} stroke={2} color="#64748B" />}
                                w={120}
                            />
                        </Box>
                    </Group>
                </Box>
            </Card.Section>
            {view === 'chart' ? (
                <ScrollArea h={height} w={width} scrollbarSize={4} pr={10}>
                    <Box w={Math.max(width, (isAdmin ? allProjectShort.length : userProjectShort.length) * 60)} >
                        <BarChart
                            h={350}
                            data={isAdmin ? allProjectShort : userProjectShort}
                            dataKey="nameShortened"
                            type="stacked"
                            withLegend
                            legendProps={{ verticalAlign: 'bottom', height: 30 }}
                            tooltipProps={{
                                content: ({ label, payload }) => <ChartTooltip label={label} payload={payload} />,
                            }}
                            fillOpacity={1}
                            series={[
                                { name: __( 'ACTIVE', 'lazytasks-project-task-management' ), color: '#2D9CDB' },
                                { name: __( 'COMPLETED', 'lazytasks-project-task-management' ), color: '#41C610' },
                                { name: __( 'OVERDUE', 'lazytasks-project-task-management' ), color: '#E62727' },
                            ]}
                            barProps={{
                                barSize: 40,
                            }}
                        />
                    </Box>
                </ScrollArea>

            ) : (
                <ProjectSummery />
            )}
        </Card>
    );
};

export default DashboardBarChart;
