'use client';

import type React from 'react';
import { useMemo, useState } from 'react';
import { Box, Typography, AccordionDetails } from '@mui/material';
import {
  _driverScheduleList,
  _geolocationList,
} from '@/shared/_mock/_roadMap';
import {
  AccordionToggleButton,
  CustomAccordion,
  CustomAccordionSummary,
} from '@/shared/components/roadmap/styled-components';
import SvgColor from '@/shared/components/svg-color';
import FontAwesome from '@/shared/components/fontawesome';
import { faCalendarPlus } from '@fortawesome/free-solid-svg-icons';
import ValidationTable, { ValidationTableConfig } from './validation-table';

const tableConfig: ValidationTableConfig = {
  trajets: [
    { id: "1", label: "Trajet 1" },
    { id: "2", label: "Trajet 2" },
    { id: "3", label: "Trajet 3" },
    { id: "4", label: "Trajet 4" },
  ],
  dates: Array(4).fill("01/03/2023"),
}

interface CombinedTableProps {
  expandedWeeks?: Record<number, boolean>;
  toggleWeek?: (weekId: number) => void;
}

export enum VerificationTableType {
  vsnschedule = 'vsn_schedule',
  geolocation = 'geolocation',
}

const ValidationCombinedTable: React.FC<CombinedTableProps> = () => {
  const [expandedWeeks, setExpandedWeeks] = useState<Record<number, boolean>>({});

  const toggleWeek = (weekId: number) => {
    setExpandedWeeks((prev) => ({
      ...prev,
      [weekId]: !prev[weekId],
    }));
  };

  const splitDatesIntoWeeks = (dates: Date[]): Date[][] => {
    const weeks: Date[][] = [];
    let currentWeek: Date[] = [];

    dates.forEach((date) => {
      if (date.getDay() === 0 && currentWeek.length > 0) {
        weeks.push(currentWeek);
        currentWeek = [];
      }
      currentWeek.push(date);
    });

    if (currentWeek.length > 0) {
      weeks.push(currentWeek);
    }

    return weeks;
  };

  const weeksOfMonth = useMemo(() => {
    const today = new Date();
    const start = new Date(today.getFullYear(), today.getMonth(), 1);
    const dates = [];
    while (start.getMonth() === today.getMonth()) {
      dates.push(new Date(start));
      start.setDate(start.getDate() + 1);
    }
    const splitIntoWeeks = splitDatesIntoWeeks(dates);
    return splitIntoWeeks;
  }, []);

  return (
    <>
      <Box sx={{ bgcolor: 'white', borderRadius: '12px', mt: 3 }}>
        <Box
          sx={{ borderBottom: `2px solid ${expandedWeeks[0] ? '#746CD4' : '#E0DDF8'}`, mb: '12px' }}
        >
          <Typography
            variant="h5"
            gutterBottom
            component="div"
            sx={{
              textAlign: 'center',
              color: 'primary.main',
              p: 3,
              fontWeight: '600',
            }}
          >
            Validation de la feuille de route
          </Typography>
          <Box sx={{ px: 3, mb: 2 }}>
            <Typography sx={{ mb: 1, color: 'primary.main', fontWeight: 600 }}>
              Légende des couleurs
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Box sx={{ width: 16, height: 16, borderRadius: '50%', bgcolor: 'success.light' }} />
              <Typography variant="body2">
                La date présente dans le planning théorique du chauffeur
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Box sx={{ width: 16, height: 16, borderRadius: '50%', bgcolor: 'info.light' }} />
              <Typography variant="body2">La date saisie par le chauffeure</Typography>
            </Box>
          </Box>
        </Box>
        {weeksOfMonth.map((week, weekIndex) => {
          const isExpanded = expandedWeeks[weekIndex] || false;
          return (
            <CustomAccordion
              key={weekIndex}
              expanded={isExpanded}
            >
              <CustomAccordionSummary isExpanded={isExpanded} onIconClick={() => toggleWeek(weekIndex)}>
                <Box
                  sx={{
                    position: 'relative',
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                  }}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <SvgColor
                      src="/assets/icons/ic_date.svg"
                      sx={{ color: 'primary.main', width: 14 }}
                    />
                    <Typography sx={{ color: 'text.secondary', fontWeight: 500 }}>
                      Total des jours saisis: 2
                    </Typography>
                  </Box>

                  <Typography
                    sx={{
                      position: 'absolute',
                      left: '50%',
                      transform: 'translateX(-50%)',
                      color: isExpanded ? 'primary.main' : 'inherit',
                      fontWeight: 500,
                    }}
                  >
                    Semaine {weekIndex + 1}
                  </Typography>

                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, ml: 'auto' }}>
                    <FontAwesome icon={faCalendarPlus} width={16} sx={{ color: 'error.main' }} />
                    <Typography sx={{ color: 'text.secondary', fontWeight: 500 }}>
                      Total des jours restants: 5
                    </Typography>
                  </Box>
                </Box>
              </CustomAccordionSummary>
              <AccordionDetails>
                <Box
                  sx={{
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'flex-start',
                  }}
                >
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1 }}>
                    <ValidationTable tableConfig={tableConfig} />
                  </Box>
                </Box>
              </AccordionDetails>
              <AccordionToggleButton isExpanded={isExpanded} onClick={()=> toggleWeek(weekIndex)} />
            </CustomAccordion>
          );
        })}
      </Box>
    </>
  );
};

export default ValidationCombinedTable;
