import React, { useMemo } from 'react';
import { Card, Group, Text, Box, ThemeIcon, Stack, Flex, Progress, Tooltip } from '@mantine/core';
import { IconLayoutList } from '@tabler/icons-react';
import { translate } from '../../../../utils/i18n';
import { isTaskComplete } from './reportUtils';

const colorForPct = (pct) => {
    if (pct < 30) return '#EF4444';
    if (pct < 60) return '#ED7D31';
    return '#39758D';
};

const SectionProgressBar = ({ tasks = [], sections = [], statuses = [], sectionOrder = [], sectionsMap = {} }) => {
    const rows = useMemo(() => {
        const byId = new Map();
        const ensure = (id, name) => {
            if (!byId.has(id)) byId.set(id, { id, name: name || translate('No Section'), total: 0, completed: 0 });
            return byId.get(id);
        };

        for (const s of sections) {
            if (s && s.id != null) ensure(String(s.id), s.name);
        }

        for (const t of tasks) {
            const sid = t.task_section_id != null ? t.task_section_id : t.section_id;
            const id = sid != null ? String(sid) : 'none';
            const row = ensure(id, id === 'none' ? translate('No Section') : null);
            row.total += 1;
            if (isTaskComplete(t, statuses, sections)) row.completed += 1;
        }

        const orderIndex = new Map();
        sectionOrder.forEach((key, idx) => {
            const secId = sectionsMap?.[key]?.id;
            if (secId != null) orderIndex.set(String(secId), idx);
        });

        return Array.from(byId.values())
            .filter((r) => r.total > 0)
            .map((r) => ({ ...r, pct: r.total > 0 ? Math.round((r.completed / r.total) * 100) : 0 }))
            .sort((a, b) => {
                const ai = orderIndex.has(a.id) ? orderIndex.get(a.id) : Number.POSITIVE_INFINITY;
                const bi = orderIndex.has(b.id) ? orderIndex.get(b.id) : Number.POSITIVE_INFINITY;
                if (ai !== bi) return ai - bi;
                return a.name.localeCompare(b.name);
            });
    }, [tasks, sections, statuses, sectionOrder, sectionsMap]);

    return (
        <Card padding="md" radius="md" withBorder>
            <Card.Section withBorder inheritPadding py="xs" className="bg-[#EBF1F4] mb-2">
                <Group gap="xs">
                    <ThemeIcon size="sm" radius="sm" variant="light" color="#39758D">
                        <IconLayoutList size={14} />
                    </ThemeIcon>
                    <Text fw={600} size="sm">{translate('Section Progress')}</Text>
                </Group>
            </Card.Section>

            {rows.length === 0 ? (
                <Flex align="center" justify="center" mih={120}>
                    <Text c="dimmed" size="sm">{translate('No sections with tasks')}</Text>
                </Flex>
            ) : (
                <Stack gap="sm" py="xs" px="xs">
                    {rows.map((r) => (
                        <Group key={r.id} gap="md" wrap="nowrap" align="center">
                            <Box style={{ flex: '0 0 160px', minWidth: 0 }}>
                                <Tooltip label={r.name} withinPortal disabled={r.name.length < 22}>
                                    <Text size="sm" fw={600} truncate>{r.name}</Text>
                                </Tooltip>
                            </Box>
                            <Box style={{ flex: 1, minWidth: 0 }}>
                                <Progress.Root size="xl" radius="sm">
                                    <Progress.Section value={r.pct} color={colorForPct(r.pct)}>
                                        {r.pct >= 12 && (
                                            <Progress.Label>{r.pct}%</Progress.Label>
                                        )}
                                    </Progress.Section>
                                </Progress.Root>
                            </Box>
                            <Box style={{ flex: '0 0 80px', textAlign: 'right' }}>
                                <Text size="sm" fw={600}>
                                    {r.completed}
                                    <Text span c="dimmed" fw={500}> / {r.total}</Text>
                                </Text>
                            </Box>
                        </Group>
                    ))}
                </Stack>
            )}
        </Card>
    );
};

export default SectionProgressBar;
