"use client"

import { useMemo } from "react"
import { Stack, Typography } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import type { DepartmentList } from "@/shared/types/infrastructure"
import { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import { TableColumn, TableType } from "@/shared/types/common"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import DepartmentTableRow from "./department-row"
import DepartmentForm from "./department-form"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { useDepartmentTable } from "../hooks/use-department-table"

export const INITIAL_DEPARTMENT_DATA: DepartmentList = {
  id: '',
  name: '',
  address: '',
  description: '',
  createdAt: new Date().toISOString().split('T')[0],
  active: true,
};

export const DEFAULT_TABLE_HEAD: TableColumn[] = [
  { id: "name", label: "Nom", type: "text" },
  { id: "address", label: "Adresse", type: "text" },
  { id: "description", label: "Description", type: "text" },
  { id: "createdAt", label: "Date de création", type: "date" },
  { id: "", label: "Action" },
];

const departmentTabsConfig: TabConfig<DepartmentList> = {
  type: TableType.Departement,
  listTitle: "Liste départements",
  newItemTitle: "Nouveau département",
  initialData: INITIAL_DEPARTMENT_DATA,
  getItemCode: (department) => department.name,
}

export default function DepartmentListView() {

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<DepartmentList>(departmentTabsConfig)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalDepartments,
    sortBy,
    sortDirection,
  } = useDepartmentTable()

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

  const renderRow = (row: DepartmentList) => (
    <DepartmentTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleEdit}
      handleCopy={handleCopy}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      handleOpenConsult={handleView}
    />
  )

  const isList = activeTab === "list"

  return (
    <>
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
        <TableControlBar
          type={TableType.Departement}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
        />
      </Stack>

      <ConditionalComponent isValid={isList}>
        <Typography variant="h5" sx={{ mb: 2, color: "primary.main", fontWeight: "bold" }}>
          Liste Départements
        </Typography>
      </ConditionalComponent>

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

      <ConditionalComponent
        isValid={isList}
        defaultComponent={
          <DepartmentForm
            department={activeTabData?.content as DepartmentList}
            onEdit={handleEdit}
            onClose={(force) => handleCancel(activeTab, force)}
            mode={activeTabData?.mode || "add"}
            tableHead={tableHead}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        }
      >
        <>
          <TableManager
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
            fixedHeight="calc(100vh - 320px)"
            onPageChange={onPageChange}
            onRowsPerPageChange={onRowsPerPageChange}
            rowsPerPage={rowsPerPage || 20}
            page={page || 0}
            count={totalDepartments}
            sortBy={sortBy || 'id'}
            sortDirection={sortDirection || 'desc'}
          />
        </>
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </>
  )
}
