'use client';

import type React from 'react';
import { useEffect, useMemo, useState } from 'react';
import { Box, Typography, AccordionDetails, Table, TableBody } 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 './combined-table-validation-header';
import ValidationCombinedTableHeader from './combined-table-validation-header';
import { StyledTableContainer } from '@/shared/theme/css';
import ValidationCombinedTableRow from './combined-table-validation-row';
import { CombinedTableDay, WorkedDay } from '@/shared/types/roadMap';
import dayjs from 'dayjs';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';

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

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

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

  const driverRoadMapDetails = useRoadMapStore((state) => state.driverRoadMapDetails);
  const getDriverRoadMap = useRoadMapStore((state) => state.getDriverRoadMap);

  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(2025, 5, 1);
    const start = new Date(today.getFullYear(), today.getMonth(), 2);
    const dates: Date[] = [];
    while (start.getMonth() === today.getMonth()) {
      dates.push(new Date(start));
      start.setDate(start.getDate() + 1);
    }
    const splitIntoWeeks = splitDatesIntoWeeks(dates);
    return splitIntoWeeks;
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      await getCombinedTable(5, '2025-06-01');
      await getDriverRoadMap(driverId, date);
    };

    fetchData();
  }, []);

  const getDriverRouteSheetData = (date: Date): WorkedDay | undefined => {
    return driverRoadMapDetails?.workedDays.find((day) =>
      dayjs(day.date).isSame(dayjs(date), 'day')
    );
  };
  const getCombinedTableData = (date: Date): CombinedTableDay | undefined => {
    if (!combinedTable || !combinedTable.combinedTableDayList) {
      return undefined;
    }
    return combinedTable.combinedTableDayList.find((day) =>
      dayjs(day.date).isSame(dayjs(date), 'day')
    );
  };
  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 }}>
                    <StyledTableContainer
                      sx={{
                        maxHeight: '486px',
                      }}
                    >
                      <Table stickyHeader>
                        <ValidationCombinedTableHeader />
                        <TableBody>
                          {week.map((date, index) => (
                            <ValidationCombinedTableRow
                              key={index}
                              date={date}
                              driverRouteSheetRow={getDriverRouteSheetData(date)}
                              combinedTableRow={getCombinedTableData(date)}
                              dayId={getCombinedTableData(date)?.id || 1}
                            />
                          ))}
                        </TableBody>
                      </Table>
                    </StyledTableContainer>
                  </Box>
                </Box>
              </AccordionDetails>
              <AccordionToggleButton
                isExpanded={isExpanded}
                onClick={() => toggleWeek(weekIndex)}
              />
            </CustomAccordion>
          );
        })}
      </Box>
    </>
  );
};

export default ValidationCombinedTable;
