"use client"
import React, { useEffect, useState } from "react"
import { Box, Stack, Tab } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import { TableType } from "@/shared/types/common"
import { useInterventionTabs } from "../hooks/use-intervention-tabs"
import { useInterventionTable } from "../hooks/use-intervention-table"
import { type IIntervention, InterventionTab } from "@/shared/types/flottes/intervention"
import TableManager from "@/shared/components/table/table-manager"
import InterventionTableRow from "./intervention-table-row"
import InterventionForm from "./intervention-new-view"
import { StyledFilterTabs } from "@/shared/theme/css"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"
import { useSearchParams } from "next/navigation"
import { enqueueSnackbar } from "notistack"

export default function InterventionListView() {
  const [activeMainTab, setActiveMainTab] = useState<InterventionTab>(InterventionTab.EnAttente)
  const searchParams = useSearchParams()

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
    handleTabAddWithContent
  } = useInterventionTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport
  } = useInterventionTable();

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

  useEffect(() => {
    const openView = searchParams.get("openView")

    if (openView === "true") {
      const storedData = sessionStorage.getItem("pendingInterventionData")

      if (storedData) {
        try {
          const interventionData: IIntervention = JSON.parse(storedData)
          handleTabAddWithContent(interventionData)
          sessionStorage.removeItem("pendingInterventionData")
          window.history.replaceState({}, "", window.location.pathname)
        } catch (error) {
          enqueueSnackbar("Erreur lors de la récupération des données d'intervention", { variant: "error" })
        }
      }
    }
  }, [searchParams, handleTabAddWithContent])

  useEffect(() => {
    handleFilterChange("statut", activeMainTab, "equals")
  }, [activeMainTab, handleFilterChange])

  const handleTabChangeWrapper = (event: React.SyntheticEvent, newValue: InterventionTab) => {
    setActiveMainTab(newValue);
  };
  const renderRow = (row: IIntervention) => (
    <InterventionTableRow
      dense={table.dense}
      key={row.id}
      row={row}
      handleEditIntervention={handleEdit}
      handleDetailsIntervention={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0,-1)}
      onStatusChange={handleStatusChange}
    />
  );
  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 }}
      >
        <TableControlBar
          type={TableType.Reparation}
          buttonAddTitle='Nouvelle Réparation'
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
        />
      </Stack>
      {activeTab === 'list' ? (
        <StyledFilterTabs
          value={activeMainTab}
          onChange={handleTabChangeWrapper}
          sx={{mb:2}}        
          >
          <Tab label="En attente" value={InterventionTab.EnAttente} />
          <Tab label="En cours" value={InterventionTab.EnCours} />
          <Tab label="Clôturé" value={InterventionTab.Cloture} />
        </StyledFilterTabs>
      ) : (
        <Box sx={{minHeight:'58px'}}></Box>
      )}
      <TabsCustom
        type={TableType.Reparation}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
        />
      ) : (
        <InterventionForm
          key={activeTab}
          intervention={activeTabData?.content as IIntervention}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
          tableHead={tableHead}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}

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