"use client"
import { useEffect, useState, useCallback, useMemo } from "react"
import React from "react"

import { Box, Grid, Button } from "@mui/material"
import {
  Departements,
  type IAttendanceNotCher,
  type IAttendanceSheet,
  type IAttendanceSheetCher,
} from "@/shared/types/etablissement"
import ActionButtons from "@/shared/components/form/buttons-action"
import AttendanceSheetCher from "../components/attendance-sheet-cher"
import AttendanceSheetNotCher from "../components/attendance-sheet-not-cher"
import ExportModal from "./export-modal"
import FontAwesome from "@/shared/components/fontawesome"
import { faFileExport } from "@fortawesome/free-solid-svg-icons"
import type { ModeType } from "@/shared/types/common"
import { mockCherDetails, mockNotCherDetails } from "@/shared/_mock/_feuillePresence"
import MultiSectionContainer from "@/shared/components/form/multiForm-container"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { AttendanceSheet } from "@/shared/types/attendance-sheet"

type TabData = IAttendanceSheetCher | IAttendanceNotCher

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

interface AttendanceSheetParentProps {
  onReturn: () => void
  mode?: ModeType
  vacation?: AttendanceSheet
  initialDepartement?: string
  onClose: (isSaved: boolean) => void
  attendance: Record<string, Record<string, boolean>> | Record<number, Record<string, Record<string, boolean>>>
  updateTabAttendance: (tabId: string, attendance: Record<string, Record<string, boolean>> | Record<number, Record<string, Record<string, boolean>>>) => void
  tabId: string
}

function MultiSectionForm({
  onReturn,
  mode = "edit",
  vacation,
  initialDepartement = Departements.Cher,
  onClose,
  attendance,
  updateTabAttendance,
  tabId,
}: AttendanceSheetParentProps) {
  const [tabs, setTabs] = useState<SheetTab[]>(() => {
    const isCher = initialDepartement === Departements.Cher
    const baseData = isCher ? mockCherDetails : mockNotCherDetails
    return [
      { id: 0, data: { ...baseData } },
      { id: 1, data: { ...baseData } },
    ]
  })
  const [exportModalOpen, setExportModalOpen] = useState(false)

  useEffect(() => {
    if (!vacation) return

    setTabs((prevTabs) =>
      prevTabs.map((tab) => ({
        ...tab,
        data: {
          ...tab.data,
          ...vacation,
        },
      })),
    )
  }, [vacation])

  const handleFormChange = useCallback((tabId: number, newData: TabData) => {
    setTabs((prevTabs) => prevTabs.map((tab) => (tab.id === tabId ? { ...tab, data: newData } : tab)))
  }, [])

  // Pour NotCher: attendance simple
  const handleAttendanceChangeNotCher = useCallback(
    (newAttendance: Record<string, Record<string, boolean>>) => {
      requestAnimationFrame(() => {
        updateTabAttendance(tabId, newAttendance)
      })
    },
    [updateTabAttendance, tabId],
  )

  // Pour Cher: attendance par onglet
  const handleAttendanceChangeCher = useCallback(
    (newAttendance: Record<number, Record<string, Record<string, boolean>>>) => {
      requestAnimationFrame(() => {
        updateTabAttendance(tabId, newAttendance)
      })
    },
    [updateTabAttendance, tabId],
  )

  const exportSheets = useMemo(
    () =>
      tabs.map((tab) => ({
        id: `Feuille-${tab.id}`,
        name: `Feuille ${tab.id + 1} - ${"etablissement" in tab.data ? tab.data.etablissement : ""} (${
          "mois" in tab.data && "annee" in tab.data ? `${tab.data.mois}/${tab.data.annee}` : ""
        })`,
      })),
    [tabs],
  )

  const exportButton = useMemo(
    () => (
      <Button
        variant="outlined"
        onClick={() => setExportModalOpen(true)}
        endIcon={<FontAwesome icon={faFileExport} width={18} />}
        sx={{
          textTransform: "none",
          color: "text.secondary",
          borderColor: "divider",
          "&:hover": {
            borderColor: "primary.main",
            color: "primary.main",
          },
        }}
      >
        Exporter
      </Button>
    ),
    [],
  )

  return (
    <Box>
      <Grid container spacing={4}>
        <ConditionalComponent
          isValid={initialDepartement === Departements.Cher}
          defaultComponent={
            <AttendanceSheetNotCher
            tabs={tabs as { id: number; data: IAttendanceNotCher; isReadOnly?: boolean }[]}
            tab={tabs[0] as { id: number; data: IAttendanceNotCher; isReadOnly?: boolean }}
            mode={mode}
            handleFormChange={handleFormChange}
            attendance={attendance as Record<string, Record<string, boolean>>}
              onAttendanceChange={handleAttendanceChangeNotCher}
            />
          }
        >
          <>
            {tabs.map((tab) => (
              <MultiSectionContainer key={tab.id} id={tab.id} title="Feuille">
                <AttendanceSheetCher
                  tabs={tabs as { id: number; data: IAttendanceSheetCher; isReadOnly?: boolean }[]}
                  tab={tab as { id: number; data: IAttendanceSheetCher; isReadOnly?: boolean }}
                  mode={mode}
                  handleFormChange={handleFormChange}
                  attendance={attendance as Record<number, Record<string, Record<string, boolean>>>}
                  onAttendanceChange={handleAttendanceChangeCher}
                />
              </MultiSectionContainer>
            ))}
          </>
        </ConditionalComponent>
      </Grid>

      <Grid item xs={12} sx={{ mt: 3 }}>
        <ActionButtons
          onSave={onReturn}
          onCancel={() => onClose(false)}
          mode={mode}
          onValidate={() => void 0}
          thirdButtonText="Enregistrer Tout"
          secoundButtonText="Retourner"
          additionalButton={exportButton}
        />
      </Grid>

      <ExportModal
        open={exportModalOpen}
        onClose={() => setExportModalOpen(false)}
        onExport={() => void 0}
        sheets={exportSheets}
      />
    </Box>
  )
}

export default React.memo(MultiSectionForm)
