'use client';

import React, { useEffect, useState } from 'react';
import {
  Box,
  Stack,
  Tab,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Button,
} 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 ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

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

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = 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(() => {
    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="Preparation 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>
  );
}
