'use client';

import React from 'react';
import { useMemo, useState } from 'react';
import { Box, Typography, Divider, AccordionDetails } from '@mui/material';
import {
  AccordionToggleButton,
  CustomAccordion,
  CustomAccordionSummary,
} from './styled-components';

export enum VerificationTableType {
  vsnschedule = 'vsn_schedule',
  geolocation = 'geolocation',
  submittedRoadMap = 'submitted_roadMap',
  combinedTable = 'combined_Table',
}

interface TableConfig {
  title: string;
  columns: any[];
  data: any[];
  verificationType: VerificationTableType;
  component: React.ComponentType<any>;
}

interface WeeklyVerificationPanelProps {
  title: string;
  tableConfigs: TableConfig[];
  expandedWeeks?: Record<number, boolean>;
  toggleWeek?: (weekId: number) => void;
  date: string;
}

const WeeklyVerificationPanel: React.FC<WeeklyVerificationPanelProps> = ({
  title,
  tableConfigs,
  expandedWeeks: externalExpandedWeeks,
  toggleWeek: externalToggleWeek,
  date,
}) => {
  const [internalExpandedWeeks, setInternalExpandedWeeks] = useState<Record<number, boolean>>({});

  const expandedWeeks = externalExpandedWeeks || internalExpandedWeeks;
  const toggleWeek =
    externalToggleWeek ||
    ((weekId: number) => {
      setInternalExpandedWeeks((prev) => ({
        ...prev,
        [weekId]: !prev[weekId],
      }));
    });

  const splitDatesIntoWeeks = (dates: Date[]): Date[][] => {
    const weeks: Date[][] = [];
    for (let i = 0; i < dates.length; i += 7) {
      weeks.push(dates.slice(i, i + 7));
    }
    return weeks;
  };

  const weeksOfMonth = useMemo(() => {
    const today = new Date(date);
    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;
  }, []);

  return (
    <>
      <Box sx={{ bgcolor: 'white', borderRadius: '12px', mt: 3 }}>
        <Typography
          variant="h5"
          gutterBottom
          component="div"
          sx={{
            borderBottom: `2px solid ${expandedWeeks[0] ? '#746CD4' : '#E0DDF8'}`,
            textAlign: 'center',
            color: 'primary.main',
            p: 3,
            mb: '12px',
            fontWeight: '600',
          }}
        >
          {title}
        </Typography>

        {weeksOfMonth.map((week, weekIndex) => {
          const isExpanded = expandedWeeks[weekIndex] || false;
          return (
            <CustomAccordion key={weekIndex} expanded={isExpanded}>
              <CustomAccordionSummary
                isExpanded={isExpanded}
                onIconClick={() => toggleWeek(weekIndex)}
              >
                <Box sx={{ flexGrow: 1, display: 'flex', justifyContent: 'center' }}>
                  <Typography
                    sx={{
                      color: isExpanded ? 'primary.main' : 'inherit',
                      fontWeight: 500,
                    }}
                  >
                    Semaine {weekIndex + 1}
                  </Typography>
                </Box>
              </CustomAccordionSummary>
              <AccordionDetails>
                <Box
                  sx={{
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'flex-start',
                  }}
                >
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1 }}>
                    {tableConfigs.map((config, index) => {
                      const TableComponent = config.component;
                      const weekDatesStr = week.map((d) => d.toISOString().split('T')[0]);

                      const filteredData = config.data.filter((row) =>
                        weekDatesStr.includes(row.date)
                      );
                      return (
                        <React.Fragment key={index}>
                          {index > 0 ? (
                            <Divider
                              orientation="vertical"
                              flexItem
                              sx={{
                                mx: 1,
                                backgroundColor: 'primary.main',
                                width: '2px',
                              }}
                            />
                          ) : (
                            <></>
                          )}
                          <TableComponent
                            title={config.title}
                            columns={config.columns}
                            data={filteredData}
                            VerificationType={config.verificationType}
                            dates={week}
                          />
                        </React.Fragment>
                      );
                    })}
                  </Box>
                </Box>
              </AccordionDetails>
              <AccordionToggleButton
                isExpanded={isExpanded}
                onClick={() => toggleWeek(weekIndex)}
              />
            </CustomAccordion>
          );
        })}
      </Box>
    </>
  );
};

export default WeeklyVerificationPanel;
