"use client"

import { useState, useEffect, useCallback, useMemo } from "react"
import { Box, Typography, Grid, Table, TableBody, TableCell, TableHead, TableRow } from "@mui/material"
import type { IAttendanceNotCher } from "@/shared/types/etablissement"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import { transportFields, studentNamesFields, observationField } from "../utils/attendance-sheet-fields"
import { StyledTableContainer } from "@/shared/theme/css"
import { HeaderCellWidthColor, HeaderRow } from "@/shared/components/form/style"
import { pxToRem } from "@/shared/theme/typography"
import { PresenceStyledRow } from "@/shared/sections/contract/styles"
import { CustomCheckbox } from "@/shared/components/form/custom-checkbox"
import SignatureField from "@/shared/sections/avenant/components/signature-field"
import React from "react"
import { generateDatesNotCher, isEqual, isVacationDay, MultiTabAttendance, SimpleAttendance, WEEKDAYS_NOTCHER } from "../utils/attendance-utils"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
interface SheetTab {
  id: number
  data: IAttendanceNotCher
  isReadOnly?: boolean
}

export interface AttendanceSheetNotCherProps {
  tabs: SheetTab[]
  tab: SheetTab
  mode?: ModeType
  handleFormChange?: (tabId: number, newData: IAttendanceNotCher) => void
  attendance: SimpleAttendance
  onAttendanceChange: (attendance: SimpleAttendance) => void
}



function AttendanceSheetNotCher({
  tabs,
  tab,
  mode = "edit",
  handleFormChange,
  attendance,
  onAttendanceChange,
}: AttendanceSheetNotCherProps) {
  const [localAttendance, setLocalAttendance] = useState<Record<string, Record<string, boolean>>>(attendance || {})
  const isReadOnly = tab.isReadOnly || mode === "view"

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const dates = useMemo(() => generateDatesNotCher(tab.data.mois, tab.data.annee), [tab.data.mois, tab.data.annee, tab.data])

  useEffect(() => {
    if (!isEqual(attendance, localAttendance)) {
      setLocalAttendance(attendance || {})
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [attendance])

  const handleAttendanceChange = useCallback(
    (day: string, column: number, weekIndex: number) => {
      setLocalAttendance((prev) => {
        const dayAttendance = prev[day] || {}
        const key = `${column}-${weekIndex}`

        if (dayAttendance[key] === !dayAttendance[key]) {
          return prev
        }

        const newDayAttendance = {
          ...dayAttendance,
          [key]: !dayAttendance[key],
        }

        const newAttendance = {
          ...prev,
          [day]: newDayAttendance,
        }

        requestAnimationFrame(() => {
          if (!isEqual(newAttendance, prev)) {
            onAttendanceChange(newAttendance)

            if (handleFormChange) {
              const presentCount = Object.values(newAttendance).reduce((count, dayData) => {
                return count + Object.values(dayData).filter((value) => value).length
              }, 0)

              const updatedData = {
                ...tab.data,
                joursPresence: presentCount.toString(),
                joursAbsence: (WEEKDAYS_NOTCHER.length * dates.length - presentCount).toString(),
              }
              handleFormChange(tab.id, updatedData)
            }
          }
        })

        return newAttendance
      })
    },
    [onAttendanceChange, handleFormChange, tab.data, tab.id, dates.length],
  )

  const renderField = useCallback(
    (field: FormFieldType<IAttendanceNotCher>) => {
      return (
        <FormField
          field={field}
          value={tab.data[field.name]}
          onChange={() => void 0}
          isReadOnly={isReadOnly}
          isDrawerElement={true}
        />
      )
    },
    [tab.data, isReadOnly],
  )

  return (
    <Box sx={{ p: 3, pr: 0, bgcolor: "white" }}>
      <Typography
        variant="h6"
        align="center"
        sx={{
          fontWeight: "bold",
          mb: 2,
          color: "primary.main",
          textTransform: "uppercase",
        }}
      >
        ATTESTATION
        <br />
        DE PRÉSENCES DES ÉLÈVES
      </Typography>

      <Grid container spacing={2}>
        {transportFields.map((field) => (
          <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}

        <Grid item xs={12}>
          <Typography
            sx={{
              fontSize: pxToRem(18),
              color: "primary.main",
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            {"Informations des élèves"}
          </Typography>
        </Grid>

        {studentNamesFields.map((field) => (
          <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
        <Grid item xs={12}>
          <StyledTableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <HeaderCellWidthColor sx={{ borderTopLeftRadius: "10px" }} colSpan={2}></HeaderCellWidthColor>
                  <HeaderCellWidthColor colSpan={2} align="center">
                    Élève A
                  </HeaderCellWidthColor>
                  <HeaderCellWidthColor colSpan={2} align="center">
                    Élève B
                  </HeaderCellWidthColor>
                  <HeaderCellWidthColor colSpan={2} align="center">
                    Élève C
                  </HeaderCellWidthColor>
                  <HeaderCellWidthColor colSpan={2} align="center">
                    Élève D
                  </HeaderCellWidthColor>
                  <HeaderCellWidthColor sx={{ borderTopRightRadius: "10px" }} colSpan={2} align="center">
                    Élève E
                  </HeaderCellWidthColor>
                </TableRow>
                <TableRow>
                  <HeaderCellWidthColor sx={{ borderBottomLeftRadius: "10px" }} colSpan={2}></HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">A</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">R</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">A</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">R</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">A</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">R</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">A</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">R</HeaderCellWidthColor>
                  <HeaderCellWidthColor align="center">A</HeaderCellWidthColor>
                  <HeaderCellWidthColor sx={{ borderBottomRightRadius: "10px" }} align="center">
                    R
                  </HeaderCellWidthColor>
                </TableRow>
              </TableHead>
              <TableBody>
                {dates.map((week, weekIndex) => (
                  <React.Fragment key={`week-${weekIndex}`}>
                    <ConditionalComponent
                      isValid={weekIndex > 0}
                    >
                      <TableRow>
                        <TableCell
                          colSpan={11}
                          sx={{
                            padding: 0,
                            backgroundColor: "white",
                            height: "8px",
                          }}
                        />
                      </TableRow>
                    </ConditionalComponent>
                    {week.map((dayData, dayIndex) => {
                      const day = WEEKDAYS_NOTCHER[dayIndex]

                      if (dayData === null) return null

                      return (
                        <PresenceStyledRow key={`${day}-${weekIndex}-${dayIndex}`}>
                          <HeaderRow sx={{ pr: 0 }}>{day}</HeaderRow>
                          <HeaderRow sx={{ px: 1 }} align="center">
                            {dayData?.dayNumber || ""}
                          </HeaderRow>
                          {Array.from({ length: 10 }).map((_, colIndex) => (
                            <TableCell
                              key={`cell-${day}-${weekIndex}-${dayIndex}-${colIndex}`}
                              align="center"
                              sx={{
                                backgroundColor: isVacationDay(`${day}-${weekIndex}`, weekIndex)
                                  ? "rgba(0, 0, 0, 0.1)"
                                  : undefined,
                              }}
                            >
                              {isVacationDay(`${day}-${weekIndex}`, weekIndex) || !dayData ? null : (
                                <CustomCheckbox
                                  checked={
                                    localAttendance[`${day}-${dayData.dayNumber}`]?.[`${colIndex}-${weekIndex}`] ||
                                    false
                                  }
                                  onChange={() =>
                                    handleAttendanceChange(`${day}-${dayData.dayNumber}`, colIndex, weekIndex)
                                  }
                                />
                              )}
                            </TableCell>
                          ))}
                        </PresenceStyledRow>
                      )
                    })}
                  </React.Fragment>
                ))}
              </TableBody>
            </Table>
          </StyledTableContainer>
        </Grid>
        <Grid item xs={12}>
          {renderField(observationField)}
        </Grid>
        <Grid item xs={12} sm={6}>
          <SignatureField
            isReadOnly={true}
            hasSignature={false}
            title={"Signature et Cachet  de l'etablissement scolaire"}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <SignatureField isReadOnly={true} hasSignature={false} title={"Signature et Cachet  du transporteur"} />
        </Grid>
      </Grid>
    </Box>
  )
}

export default React.memo(AttendanceSheetNotCher)
