"use client"

import { useCallback, 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 { SectorList } from "@/shared/types/infrastructure"
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 SectorForm from "./sector-form"
import SectorTableRow from "./sector-row"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useSectorTable } from "../hooks/use-sector-table"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { useSnackbar } from "notistack"

const INITIAL_SECTOR_DATA: SectorList = {
  id: "",
  name: "",
  address: "",
  createdAt: new Date().toISOString(),
  active: true,
}

const sectorTabsConfig: TabConfig<SectorList> = {
  type: TableType.Secteur,
  listTitle: "Liste secteurs",
  newItemTitle: "Nouveau secteur",
  initialData: INITIAL_SECTOR_DATA,
  getItemCode: (sector) => sector.id,
}

export default function SectorListView() {

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalSectors,
    sortBy,
    sortDirection,
    handleStartExportInExcel,
    handleExportInPdf
  } = useSectorTable()

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

  const exportOptions = useMemo(() => [
    {
      label: "Lancer l'exportation en Excel",
      action: () => handleStartExportInExcel()
    },
    {
      label: "Exporter en PDF",
      action: () => handleExportInPdf()
    }
  ], [handleStartExportInExcel, handleExportInPdf]);

  const renderRow = (row: SectorList) => (
    <SectorTableRow
      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.Secteur}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

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

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

      <ConditionalComponent
        isValid={isList}
        defaultComponent={
          <SectorForm
            sector={activeTabData?.content as SectorList}
            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 - ${HEADER.H_DESKTOP + 195}px)`}
          onPageChange={onPageChange}
          page={page || 0}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage || 20}
          count={totalSectors}
          sortBy={sortBy || 'name'}
          sortDirection={sortDirection || 'desc'}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </>
  )
}
