"use client"

import { 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 { LotList } from "@/shared/types/infrastructure"
import { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import { TableType, TableColumn } from "@/shared/types/common"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import LotForm from "./lot-form"
import LotTableRow from "./lot-row"
import InfrastructureConditionalComponent from "@/shared/components/table/InfrastructureConditionalComponent"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { useLotTable } from "../hooks/use-lot-table"
import { useSnackbar } from "notistack"

export const INITIAL_LOT_DATA: LotList = {
  id: '',
  number: '',
  description: '',
  createdAt: new Date().toISOString().split('T')[0],
  active: true,
};

export const DEFAULT_TABLE_HEAD: TableColumn[] = [
  { id: "number", label: "Numéro de lot", type: "text" },
  { id: "description", label: "Description", type: "text" },
  { id: "createdAt", label: "Date de création", type: "date" },
  { id: "", label: "Action" },
];

const lotTabsConfig: TabConfig<LotList> = {
  type: TableType.Lot,
  listTitle: "Liste lots",
  newItemTitle: "Nouveau lot",
  initialData: INITIAL_LOT_DATA,
  getItemCode: (lot) => lot.number,
}

export default function LotListView() {

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    error,
    loading,
    clearError,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalLots,
    sortBy,
    sortDirection,
    onResetFilters
  } = useLotTable();

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

  const renderRow = (row: LotList) => (
    <LotTableRow
      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.Lot}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={onResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
        />
      </Stack>

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

      <InfrastructureConditionalComponent
        isValid={isList}
        defaultComponent={
          <LotForm
            lot={activeTabData?.content as LotList}
            onEdit={handleEdit}
            onClose={(force) => handleCancel(activeTab, force)}
            mode={activeTabData?.mode || "add"}
            tableHead={tableHead}
            updateTabContent={updateTabContent}
            tabId={activeTab}
            markTabAsSaved={markTabAsSaved}
            tabContent={activeTabData?.content as LotList}
          />
        }
      >
        <>
          <TableManager
            loading={loading}
            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={totalLots}
            sortBy={sortBy || 'id'}
            sortDirection={sortDirection || 'desc'}
          />
        </>
      </InfrastructureConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </>
  )
}
