"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",
}

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
}

const WeeklyVerificationPanel: React.FC<WeeklyVerificationPanelProps> = ({
  title,
  tableConfigs,
  expandedWeeks: externalExpandedWeeks,
  toggleWeek: externalToggleWeek,
}) => {
  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[][] = []
    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 }}>
        <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
                      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={config.data}
                            VerificationType={config.verificationType}
                          />
                        </React.Fragment>
                      )
                    })}
                  </Box>
                </Box>
              </AccordionDetails>
              <AccordionToggleButton isExpanded={isExpanded} onClick={()=> toggleWeek(weekIndex)} />
            </CustomAccordion>
          )
        })}
      </Box>
    </>
  )
}

export default WeeklyVerificationPanel

