import { useEffect } from 'react';
import { Paper, Text, Group, ThemeIcon, Box } from '@mantine/core';
import {
    IconChecklist,
    IconRefresh,
    IconCircleCheck,
    IconAlertTriangle,
} from '@tabler/icons-react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchTaskCounts } from '../Settings/store/taskSlice';
import { __, _n, sprintf } from '@wordpress/i18n';

const CARD_CONFIG = {
    total: {
        title: () => __( 'Total Tasks', 'lazytasks-project-task-management' ),
        bg: '#FCEBE0',
        iconBg: 'rgba(237,125,49,0.22)',
        iconColor: '#D46A1E',
        Icon: IconChecklist,
    },
    progress: {
        title: () => __( 'Tasks In Progress', 'lazytasks-project-task-management' ),
        bg: '#DBE5FF',
        iconBg: 'rgba(57,117,141,0.22)',
        iconColor: '#39758D',
        Icon: IconRefresh,
    },
    completed: {
        title: () => __( 'Tasks Completed', 'lazytasks-project-task-management' ),
        bg: '#E7F4E8',
        iconBg: 'rgba(16,185,129,0.22)',
        iconColor: '#10B981',
        Icon: IconCircleCheck,
    },
    overdue: {
        title: () => __( 'Overdue Tasks', 'lazytasks-project-task-management' ),
        bg: '#F9D9E0',
        iconBg: 'rgba(239,68,68,0.22)',
        iconColor: '#EF4444',
        Icon: IconAlertTriangle,
    },
};

const countFor = (taskCount, type) => {
    if (!taskCount) return 0;
    if (type === 'progress') return taskCount.pending_tasks || 0;
    if (type === 'completed') return taskCount.completed_tasks || 0;
    if (type === 'overdue') return taskCount.overdue_tasks || 0;
    return taskCount.total_tasks || 0;
};

const percentFor = (taskCount, type) => {
    if (!taskCount) return 0;
    if (type === 'progress') return taskCount.pending_tasks_percentage || 0;
    if (type === 'completed') return taskCount.completed_tasks_percentage || 0;
    if (type === 'overdue') return taskCount.overdue_tasks_percentage || 0;
    return taskCount.total_tasks_percentage || 0;
};

const DashboardCard = ({ type = 'total', dragHandle }) => {
    const dispatch = useDispatch();
    const { taskCount } = useSelector((state) => state.settings.task);
    const { xWpNonce } = useSelector((state) => state.auth.session);

    useEffect(() => {
        if (!xWpNonce) return;
        if (!taskCount || Object.keys(taskCount).length === 0) {
            dispatch(fetchTaskCounts());
        }
    }, [dispatch, xWpNonce]);

    const cfg = CARD_CONFIG[type] || CARD_CONFIG.total;
    const count = countFor(taskCount, type);
    const percent = percentFor(taskCount, type);
    const projectCount = taskCount?.total_projects || 0;

    const subtitle =
        type === 'total'
            ? sprintf(
                /* translators: %d: number of projects */
                _n( '%d project', '%d projects', projectCount, 'lazytasks-project-task-management' ),
                projectCount
            )
            : `${percent}% ${__( 'of total', 'lazytasks-project-task-management' )}`;

    return (
        <Paper
            radius="md"
            p="md"
            withBorder
            pos="relative"
            style={{
                background: cfg.bg,
                borderColor: 'transparent',
                height: '100%',
                minHeight: 110,
            }}
        >
            <Box pos="absolute" top={5} right={5} style={{ zIndex: 10 }}>
                {dragHandle}
            </Box>
            <Group justify="space-between" align="flex-start" wrap="nowrap" h="100%" className={dragHandle ? 'draggable-header cursor-grab' : ''}>
                <Box style={{ minWidth: 0 }}>
                    <Text
                        size="xs"
                        fw={700}
                        c="dimmed"
                        tt="uppercase"
                        style={{ letterSpacing: '0.3px' }}
                    >
                        {cfg.title()}
                    </Text>
                    <Text fz={28} fw={700} lh={1.1} mt={6}>
                        {count}
                    </Text>
                    <Text size="xs" c="dimmed" mt={4}>
                        {subtitle}
                    </Text>
                </Box>
                <ThemeIcon
                    size={42}
                    radius="md"
                    variant="filled"
                    style={{ background: cfg.iconBg, color: cfg.iconColor }}
                >
                    <cfg.Icon size={20} stroke={1.8} />
                </ThemeIcon>
            </Group>
        </Paper>
    );
};

export default DashboardCard;
