"use client";

import { useCallback, useMemo } from "react";
import { Box, Stack } from "@mui/material";
import { HEADER } from "@/layouts/config-layout";
import { TableType } from "@/shared/types/common";
import TabsCustom from "@/shared/components/tabs/tabs-custom";
import TableManager from "@/shared/components/table/table-manager";
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 { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog";
import { AttendanceSheet } from "@/shared/types/attendance-sheet";
import { useAttendanceTabs, AttendanceTabContent, TabContentBase } from "../hooks/use-attendance-tabs";
import { useAttendanceTable } from "../hooks/use-attendance-table";
import AttendanceForm from "./attendance-new-view";
import AttendanceDetailView from "../components/attendance-detail-view";
import { AttendanceUnion } from "../utils/attendance-utils";

export default function AttendanceListView() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleView,
    handleEdit,
    handleCancel,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useAttendanceTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    loading,
    totalAttendanceSheets,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    sortBy,
    sortDirection,
    refreshData,
  } = useAttendanceTable();
  const updateTabAttendance = useCallback(
    (tabId: string, attendance: AttendanceUnion) => {
      const currentTab = tabs.find((tab) => tab.id === tabId);
      if (currentTab && currentTab.content && currentTab.content !== 'list') {
        const updatedContent: TabContentBase = {
          ...currentTab.content,
          attendance,
        };
        updateTabContent(tabId, updatedContent);
      }
    },
    [tabs, updateTabContent],
  );
  const activeTabData = useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);
  const handleViewDetails = (row: AttendanceSheet) => {
    const detailTabContent: AttendanceTabContent = {
      id: row.id,
      data: row,
      currentStep: "sheet",
      attendance: {},
    };
    handleView(detailTabContent);
  };

  const renderRow = (row: AttendanceSheet) => (
    <AttendanceTableRow
      key={row.id}
      row={row}
      columns={tableHead.slice(0, -1)}
      refreshData={refreshData}
      handleDetailsAttendance={handleViewDetails}
    />
  );
  const handleCloseWithRefresh = (tabId: string, isSaved: boolean) => {
    if (isSaved) {
      refreshData();
    }
    handleCancel(tabId, isSaved);
  };

  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}
      />

      {activeTab === "list" ? (
        <TableManager
          filteredData={filteredData}
          table={{
            ...table,
            page: page ?? 0,
            rowsPerPage: rowsPerPage ?? 20,
            orderBy: sortBy ?? "number",
            order: sortDirection ?? "desc",
          }}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          loading={loading}
          count={totalAttendanceSheets}
          onPageChange={onPageChange}
          onRowsPerPageChange={onRowsPerPageChange}
        />
      ) : (
        activeTabData?.content && activeTabData.content !== 'list' && (
          <Box key={activeTab}>
            {activeTabData.mode === 'add' ? (
              <AttendanceForm
                attendance={activeTabData.content as AttendanceTabContent}
                onClose={(isSaved) => handleCloseWithRefresh(activeTab, isSaved)}
                updateTabContent={updateTabContent}
                updateTabAttendance={updateTabAttendance}
                tabId={activeTab}
              />
            ) : (
              <AttendanceDetailView
                key={`detail-${activeTab}-${(activeTabData.content as AttendanceTabContent).id}`}
                attendance={(activeTabData.content as AttendanceTabContent).data}
                mode={activeTabData.mode || "view"}
                onClose={(isSaved) => handleCloseWithRefresh(activeTab, isSaved)}
                onEdit={(attendance: AttendanceSheet) => {
                  const editTabContent: AttendanceTabContent = {
                    id: attendance.id,
                    data: attendance,
                    currentStep: "form",
                    attendance: {},
                  };
                  handleEdit(editTabContent);
                }}
              />
            )}
          </Box>
        )
      )}

      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={handleConfirmDialogAction}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}