"use client"

import { useState, useEffect, useCallback, useMemo } from "react"
import React from "react"
import { Box, Typography, Grid, Table, TableBody, TableCell, TableHead } from "@mui/material"
import type { IAttendanceSheetCher } from "@/shared/types/etablissement"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import { studentFields, schoolFields, summaryFields, signatureFields } 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 { BaseStyledRow, PresenceStyledRow } from "@/shared/sections/contract/styles"
import { CustomCheckbox } from "@/shared/components/form/custom-checkbox"
import SignatureField from "@/shared/sections/avenant/components/signature-field"
import { formatDateFrench, generateDatesCher, isEqual, MultiTabAttendance, WEEKDAYS_CHER } from "../utils/attendance-utils"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface SheetTab {
  id: number
  data: IAttendanceSheetCher
  isReadOnly?: boolean
}

export interface AttendanceSheetProps {
  tabs: SheetTab[]
  tab: SheetTab
  mode?: ModeType
  handleFormChange?: (tabId: number, newData: IAttendanceSheetCher) => void
  attendance: MultiTabAttendance
  onAttendanceChange: (newAttendance: MultiTabAttendance) => void
}


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

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

  const dates = useMemo(() => generateDatesCher(tab.data.mois, tab.data.annee), [tab.data.mois, tab.data.annee])


  const tabAttendance = localAttendance[tab.id] || {}

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

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

        const newTabAttendance = {
          ...tabAttendance,
          [day]: {
            ...dayAttendance,
            [key]: !dayAttendance[key],
          },
        }

        const newAttendance = {
          ...prev,
          [tabId]: newTabAttendance,
        }

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

            if (handleFormChange) {
              const tab = tabs.find((t) => t.id === tabId)
              if (tab) {
                const presentCount = Object.values(newTabAttendance).reduce((count, dayData) => {
                  return count + Object.values(dayData).filter((value) => value).length
                }, 0)

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

        return newAttendance
      })
    },
    [onAttendanceChange, handleFormChange, tabs, dates.length],
  )

  const renderField = useCallback(
    (tabId: number, field: FormFieldType<IAttendanceSheetCher>, isReadOnly: boolean) => {
      const tab = tabs.find((t) => t.id === tabId)
      if (!tab) return null

      return (
        <FormField
          field={field}
          value={tab.data[field.name]}
          onChange={() => void 0}
          isReadOnly={isReadOnly}
          isDrawerElement={true}
        />
      )
    },
    [tabs],
  )

  return (
    <Box sx={{ p: 3, bgcolor: "white" }}>
      <Grid container spacing={2} sx={{ mb: 3 }}>
        {schoolFields.map((field) => (
          <Grid item xs={12} sm={6} key={field.name}>
            {renderField(tab.id, field, isReadOnly)}
          </Grid>
        ))}
        <Grid item xs={12}>
          <Typography
            sx={{
              fontSize: pxToRem(18),
              color: "primary.main",
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            {"Informations d'élève"}
          </Typography>
        </Grid>
        {studentFields.map((field) => (
          <Grid item xs={12} sm={6} key={field.name}>
            {renderField(tab.id, field, isReadOnly)}
          </Grid>
        ))}
      </Grid>

      <Box sx={{ mb: 3 }}>
        <Typography
          sx={{
            mb: 1,
            fontSize: pxToRem(16),
            color: "primary.main",
            fontWeight: 500,
            display: "flex",
            justifyContent: "center",
          }}
        >

          {formatDateFrench(tab.data.mois, tab.data.annee)}
        </Typography>
        <StyledTableContainer>
          <Table size="small">
            <TableHead>
              <BaseStyledRow>
                <HeaderCellWidthColor></HeaderCellWidthColor>
                {dates.map((dateRange, index) => (
                  <HeaderCellWidthColor align="center" key={`date-range-${index}`} colSpan={2}>
                    Date Du: {dateRange.start.getDate()} Au {dateRange.end.getDate()}
                  </HeaderCellWidthColor>
                ))}
              </BaseStyledRow>
            </TableHead>
            <TableBody>
              {WEEKDAYS_CHER.map((day, rowIndex) => (
                <PresenceStyledRow key={day}>
                  <HeaderRow>{day}</HeaderRow>
                  {dates.map((_, colIndex) => (
                    <React.Fragment key={`fragment-${day}-${colIndex}`}>
                      <TableCell key={`cell-${day}-${colIndex}-1`} align="center">
                        <ConditionalComponent
                          isValid={!isReadOnly}
                        >
                          <CustomCheckbox
                            checked={tabAttendance[day]?.[`${colIndex}-0`] || false}
                            onChange={() => handleAttendanceChange(tab.id, day, colIndex, 0)}
                          />
                        </ConditionalComponent>
                      </TableCell>
                      <TableCell key={`cell-${day}-${colIndex}-2`} align="center">
                        <ConditionalComponent
                          isValid={!isReadOnly}
                        >
                          <CustomCheckbox
                            checked={tabAttendance[day]?.[`${colIndex}-1`] || false}
                            onChange={() => handleAttendanceChange(tab.id, day, colIndex, 1)}
                          />
                        </ConditionalComponent>
                      </TableCell>
                    </React.Fragment>
                  ))}
                </PresenceStyledRow>
              ))}
            </TableBody>
          </Table>
        </StyledTableContainer>
      </Box>

      <Grid container spacing={2}>
        {summaryFields.map((field) => (
          <Grid item xs={12} sm={6} key={field.name}>
            {renderField(tab.id, field, isReadOnly)}
          </Grid>
        ))}
        {signatureFields.map((field) => (
          <Grid item xs={12} sm={6} key={field.name}>
            {renderField(tab.id, field, isReadOnly)}
          </Grid>
        ))}
        <Grid item xs={12} sm={7} key={"signature"}>
          <SignatureField isReadOnly={true} hasSignature={false} />
        </Grid>
      </Grid>
    </Box>
  )
}

export default React.memo(AttendanceSheetCher)
