import {
    faClock,
    faListCheck,
    faCalendarDays
} from '@fortawesome/free-solid-svg-icons';
import PieCharts from '@/shared/components/charts/pie-charts';
import { Box, Grid, Card, Typography, alpha } from '@mui/material';
import { IDemandeAbsence } from '@/shared/types/leave';
import LeaveBalanceCard from './leave-balance-card';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';
import { useEffect, useCallback } from 'react';

interface AbsenceOverviewProps {
    data: IDemandeAbsence[];
}

export default function AbsenceOverview({ data }: AbsenceOverviewProps) {
    const { statistics, fetchStatistics, absences } = useAbsenceStoree();

    const refreshData = useCallback(() => {
        const userId = localStorage.getItem("userId");
        if (userId) {
            fetchStatistics(parseInt(userId));
        }
    }, [fetchStatistics]);
    useEffect(() => {
        refreshData();
    }, [refreshData]);
    useEffect(() => {
        refreshData();
    }, [absences, refreshData]);
    useEffect(() => {
        const intervalId = setInterval(refreshData, 30000);
        return () => clearInterval(intervalId);
    }, [refreshData]);
    const stateMapping = {
        'Waiting': 'En attente',
        'Approved': 'Validé',
        'Rejected': 'Refusé',
        'Unprocessed': 'En attente'
    };

    const waitingCount = (statistics?.byState?.Waiting || 0) + (statistics?.byState?.Unprocessed || 0);
    const approvedCount = statistics?.byState?.Approved || 0;
    const rejectedCount = statistics?.byState?.Rejected || 0;
    const total = waitingCount + approvedCount + rejectedCount;



    const charts = [
        {
            title: 'Répartition par statut',
            data: statistics ? [
                {
                    id: 'En attente',
                    value: waitingCount,
                    label: `En attente (${waitingCount}) ${total > 0 ? Math.round((waitingCount / total) * 100) : 0}%`,
                    color: '#F9B90B'
                },
                {
                    id: 'Validé',
                    value: approvedCount,
                    label: `Validé (${approvedCount}) ${total > 0 ? Math.round((approvedCount / total) * 100) : 0}%`,
                    color: '#36B37E'
                },
                {
                    id: 'Refusé',
                    value: rejectedCount,
                    label: `Refusé (${rejectedCount}) ${total > 0 ? Math.round((rejectedCount / total) * 100) : 0}%`,
                    color: '#FF3434'
                },
            ].filter(item => item.value > 0) : []
        },
    ];

    console.log('Chart data:', charts);

    const stats = statistics ? [
        {
            title: 'Total Demandes',
            total: statistics.totals.total,
            icon: faListCheck,
            color: '#5176FE',
        },
        {
            title: 'Total Absences',
            total: statistics.totals.absences,
            icon: faClock,
            color: '#F9B90B',
        },
        {
            title: 'Total Congés',
            total: statistics.totals.leaves,
            icon: faCalendarDays,
            color: '#36B37E',
        },
    ] : [];

    // Map leave balances from statistics
    const balances = statistics ? [
        {
            type: 'Annuel',
            used: 0,
            total: statistics.leaveBalance.LEAVE_PAID || 0,
            color: '#FF6B6B',
        },
        {
            type: 'Maladie',
            used: 0,
            total: statistics.leaveBalance.LEAVE_MALADIE || 0,
            color: '#4ECDC4',
        },
        {
            type: 'RTT',
            used: 0,
            total: statistics.leaveBalance.LEAVE_RTT || 0,
            color: '#96CEB4',
        },
    ] : [];

    return (
        <Box sx={{ width: '100%' }}>
            <Grid container spacing={2}>
                {/* Status Distribution Chart */}
                <Grid item xs={12} md={4}>
                    <Card
                        sx={{
                            p: 2,
                            height: '100%',
                            borderRadius: 2,
                            border: (theme) => `1px solid ${theme.palette.divider}`,
                            boxShadow: 'none',
                            bgcolor: 'background.paper',
                            transition: 'all 0.3s ease',
                            '&:hover': {
                                boxShadow: '0 4px 20px 0 rgba(0,0,0,0.05)',
                                bgcolor: (theme) => alpha(theme.palette.primary.main, 0.02),
                                borderColor: (theme) => alpha(theme.palette.primary.main, 0.2),
                            }
                        }}
                    >
                        <Typography
                            variant="h6"
                            sx={{
                                mb: 2,
                                color: (theme) => theme.palette.primary.main,
                                fontWeight: 600
                            }}
                        >
                            Répartition par statut
                        </Typography>
                        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 'calc(100% - 40px)' }}>
                            {statistics && <PieCharts charts={charts} fullWidth />}
                        </Box>
                    </Card>
                </Grid>

                {/* Leave Balance Card */}
                <Grid item xs={12} md={4}>
                    {statistics && <LeaveBalanceCard balances={balances} />}
                </Grid>

                {/* Stats Cards */}
                <Grid item xs={12} md={4}>
                    <Card
                        sx={{
                            p: 2,
                            height: '100%',
                            borderRadius: 2,
                            border: (theme) => `1px solid ${theme.palette.divider}`,
                            boxShadow: 'none',
                            bgcolor: 'background.paper',
                            transition: 'all 0.3s ease',
                            '&:hover': {
                                boxShadow: '0 4px 20px 0 rgba(0,0,0,0.05)',
                                bgcolor: (theme) => alpha(theme.palette.primary.main, 0.02),
                                borderColor: (theme) => alpha(theme.palette.primary.main, 0.2),
                            }
                        }}
                    >
                        <Typography
                            variant="h6"
                            sx={{
                                mb: 2,
                                color: (theme) => theme.palette.primary.main,
                                fontWeight: 600
                            }}
                        >
                            Statistiques
                        </Typography>
                        <Grid container spacing={1} sx={{ height: 'calc(100% - 40px)' }}>
                            {stats.map((stat, index) => (
                                <Grid item xs={12} key={index}>
                                    <Box
                                        sx={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            p: 1,
                                            borderRadius: 1,
                                            border: '1px solid',
                                            borderColor: alpha(stat.color, 0.2),
                                            bgcolor: alpha(stat.color, 0.05),
                                            transition: 'all 0.3s ease',
                                            '&:hover': {
                                                boxShadow: '0 2px 10px 0 rgba(0,0,0,0.05)',
                                                bgcolor: alpha(stat.color, 0.1),
                                                borderColor: alpha(stat.color, 0.3),
                                                transform: 'translateY(-2px)'
                                            },
                                            cursor: 'pointer'
                                        }}
                                    >
                                        <Box
                                            sx={{
                                                width: 40,
                                                height: 40,
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                borderRadius: '50%',
                                                backgroundColor: alpha(stat.color, 0.1),
                                                color: stat.color,
                                                mr: 2,
                                                transition: 'all 0.3s ease',
                                                '&:hover': {
                                                    backgroundColor: alpha(stat.color, 0.2),
                                                }
                                            }}
                                        >
                                            <Box component="span" sx={{ fontSize: 20, color: stat.color }}>
                                                {stat.total}
                                            </Box>
                                        </Box>
                                        <Typography variant="body1" sx={{ fontWeight: 'medium' }}>
                                            {stat.title}
                                        </Typography>
                                    </Box>
                                </Grid>
                            ))}
                        </Grid>
                    </Card>
                </Grid>
            </Grid>
        </Box>
    );
}