"use client"

import { useMemo, useCallback } from "react"
import { Box, Stack } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import type { IAttendanceSheet } from "@/shared/types/etablissement"
import { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import { TableType } from "@/shared/types/common"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import {
  _attendanceSheet,
  DEFAULT_ATTENDANCE_TABLE_HEAD,
  INITIAL_ATTENDANCE_DATA,
} from "@/shared/_mock/_feuillePresence"
import AttendanceTableRow from "./attendance-table-row"
import { AddButton } from "@/shared/components/table/styles"
import FontAwesome from "@/shared/components/fontawesome"
import { faFileExport } from "@fortawesome/free-solid-svg-icons"
import AttendanceForm from "./attendance-new-view"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { isEqual, type AttendanceUnion } from "../utils/attendance-utils"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
export type AttendanceTabContent = {
  data: IAttendanceSheet
  currentStep: "form" | "sheet"
  id: string
  attendance: AttendanceUnion
}

const etablissementConfig: TableConfig<IAttendanceSheet> = {
  initialData: _attendanceSheet,
  defaultTableHead: DEFAULT_ATTENDANCE_TABLE_HEAD,
}

const etablissementTabsConfig: TabConfig<AttendanceTabContent> = {
  type: TableType.AttendanceSheet,
  listTitle: "Historique feuille de présence",
  newItemTitle: "Nouvelle feuille de présence",
  initialData: {
    data: INITIAL_ATTENDANCE_DATA,
    currentStep: "form",
    id: INITIAL_ATTENDANCE_DATA.id,
    attendance: {},
  },
  getItemCode: (attendance) => attendance.data.number,
}

export default function AttendanceListView() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<AttendanceTabContent>(etablissementTabsConfig)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<IAttendanceSheet>(etablissementConfig)

  const activeTabData = useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab)
  }, [tabs, activeTab])

  const updateTabAttendance = useCallback(
    (tabId: string, attendance: Record<string, Record<string, boolean>> | Record<number, Record<string, Record<string, boolean>>>) => {
      const currentTab = tabs.find((tab) => tab.id === tabId)
      if (currentTab && currentTab.content) {
        if (isEqual((currentTab.content as AttendanceTabContent).attendance, attendance)) {
          return
        }

        const updatedContent: AttendanceTabContent = {
          ...(currentTab.content as AttendanceTabContent),
          attendance,
        }
        updateTabContent(tabId, updatedContent)
      }
    },
    [tabs, updateTabContent],
  )

  const renderRow = useCallback(
    (row: IAttendanceSheet) => <AttendanceTableRow key={row.id} row={row} columns={tableHead.slice(0, -1)} />,
    [tableHead],
  )

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
        <AddButton onClick={handleTabAdd} variant="contained" endIcon={<FontAwesome width={16} icon={faFileExport} />}>
          Générer feuille de présence
        </AddButton>
      </Stack>

      <TabsCustom
        type={TableType.AttendanceSheet}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      <ConditionalComponent
        isValid={activeTab === "list"}
        defaultComponent={
          <AttendanceForm
          key={activeTab}
          vacation={activeTabData?.content as AttendanceTabContent}
          onClose={(isSaved) => handleCancel(activeTab, isSaved)}
          updateTabContent={updateTabContent}
          updateTabAttendance={updateTabAttendance}
          tabId={activeTab}
        />
        }
      >
        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
