import { useMemo } from 'react';
import { Card, Group, Text, Box, ThemeIcon, Stack, Flex, SimpleGrid } from '@mantine/core';
import { DonutChart } from '@mantine/charts';
import { IconChartPie } from '@tabler/icons-react';
import { __ } from '@wordpress/i18n';

const FALLBACK_COLORS = ['#94A3B8', '#6B7FD7', '#ED7D31', '#10B981', '#8B5CA7', '#4EB097', '#EF4444'];

const StatusDonut = ({ tasks = [], statuses = [] }) => {
    const { chartData, total } = useMemo(() => {
        const counts = new Map();
        for (const t of tasks) {
            const key = t.internal_status_id != null
                ? String(t.internal_status_id)
                : t.internal_status?.id != null
                    ? String(t.internal_status.id)
                    : 'none';
            counts.set(key, (counts.get(key) || 0) + 1);
        }

        const statusById = new Map(statuses.map((s) => [String(s.id), s]));
        const data = [];
        let idx = 0;
        counts.forEach((value, key) => {
            if (value === 0) return;
            const status = statusById.get(key);
            const name = status?.name || __( 'No Status', 'lazytasks-project-task-management' );
            const color = status?.color_code || FALLBACK_COLORS[idx % FALLBACK_COLORS.length];
            data.push({ name, value, color });
            idx += 1;
        });
        data.sort((a, b) => b.value - a.value);
        return { chartData: data, total: tasks.length };
    }, [tasks, statuses]);

    return (
        <Card padding="md" radius="md" withBorder h="100%">
            <Card.Section withBorder inheritPadding py="xs" className="bg-[#EBF1F4] mb-2">
                <Group gap="xs">
                    <ThemeIcon size="sm" radius="sm" variant="light" color="#39758D">
                        <IconChartPie size={14} />
                    </ThemeIcon>
                    <Text fw={600} size="sm">{__( 'Status Distribution', 'lazytasks-project-task-management' )}</Text>
                </Group>
            </Card.Section>

            {chartData.length === 0 ? (
                <Flex align="center" justify="center" mih={240}>
                    <Text c="dimmed" size="sm">{__( 'No tasks available', 'lazytasks-project-task-management' )}</Text>
                </Flex>
            ) : (
                <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="lg" verticalSpacing="md" p="sm" style={{ alignItems: 'center' }}>
                    <Box style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
                        <DonutChart
                            data={chartData}
                            withTooltip
                            tooltipDataSource="segment"
                            withLabels={false}
                            size={200}
                            thickness={25}
                            strokeWidth={1}
                            paddingAngle={0}
                        />
                        <Box
                            style={{
                                position: 'absolute',
                                top: '50%',
                                left: '50%',
                                transform: 'translate(-50%, -50%)',
                                textAlign: 'center',
                                pointerEvents: 'none',
                            }}
                        >
                            <Text fw={700} fz={26} lh={1}>{total}</Text>
                            <Text fz={11} mt={3} c="dimmed" tt="uppercase" style={{ letterSpacing: '0.5px' }}>
                                {__( 'Tasks', 'lazytasks-project-task-management' )}
                            </Text>
                        </Box>
                    </Box>
                    <Stack gap={8}>
                        {chartData.map((d) => {
                            const pct = total > 0 ? Math.round((d.value / total) * 100) : 0;
                            return (
                                <Group
                                    key={d.name}
                                    gap={10}
                                    wrap="nowrap"
                                    px={10}
                                    py={8}
                                    className="rounded-md transition-colors hover:bg-gray-50 cursor-default"
                                >
                                    <Box w={12} h={12} style={{ background: d.color, borderRadius: 3, flexShrink: 0 }} />
                                    <Text fz={13} fw={500} style={{ flex: 1, minWidth: 0 }} truncate>{d.name}</Text>
                                    <Text fz={13} fw={700}>
                                        {d.value}
                                        <Text span fz={11} c="dimmed" fw={500} ml={6}>({pct}%)</Text>
                                    </Text>
                                </Group>
                            );
                        })}
                    </Stack>
                </SimpleGrid>
            )}
        </Card>
    );
};

export default StatusDonut;
