"use client"

import { useCallback, useEffect, 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 InfrastructureConditionalComponent from "@/shared/components/table/InfrastructureConditionalComponent"
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.name,
}

export default function SectorListView() {

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    error,
    loading,
    clearError,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalSectors,
    sortBy,
    sortDirection,
    handleStartExportInExcel,
    handleExportInPdf,
    onResetFilters
  } = 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"

  useEffect(() => {
    if (error) {
      enqueueSnackbar(error, { variant: 'error' })
      clearError()
    }
  }, [error, enqueueSnackbar, clearError])

  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={onResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

     

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

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