'use client';

import React, { useEffect } from 'react';
import { Box, IconButton, Stack } from '@mui/material';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import { TableType } from '@/shared/types/common';
import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { IChauffeur } from '@/shared/types/chauffeur';
import { _chauffeurs, DEFAULT_CHAUFFEUR_TABLE_HEAD, INITIAL_CHAUFFEUR_DATA } from '@/shared/_mock/_chauffeurs';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileExport, faRotate, faSquarePlus } from '@fortawesome/free-solid-svg-icons';
import { iconButtonStyles } from '@/shared/theme/css';
import { AddButton } from '@/shared/components/table/styles';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import TableManager from '@/shared/components/table/table-manager';
import ChauffeurTableRow from './chauffeur-row';
import NewChauffeurForm from './chauffeur-new';
import ExportButton from '@/shared/components/table/table-export-button';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

const chauffeurTabsConfig: TabConfig<IChauffeur> = {
  type: 'chauffeur',
  listTitle: 'Liste des chauffeurs',
  newItemTitle: 'Nouveau chauffeur',
  initialData: INITIAL_CHAUFFEUR_DATA,
  getItemCode: (chauffeur) => chauffeur.numeroChauffeur,
};

const chauffeurTableConfig: TableConfig<IChauffeur> = {
  initialData: _chauffeurs,
  defaultTableHead: DEFAULT_CHAUFFEUR_TABLE_HEAD,
};

export default function ChauffeurList() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<IChauffeur>(chauffeurTabsConfig);


  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<IChauffeur>(chauffeurTableConfig);
   const renderRow = (row: IChauffeur) => (
       <ChauffeurTableRow
            dense={table.dense}
            key={row.id}
            row={row}
            handleDetails={handleView}
            selected={table.selected.includes(row.id)}
            onSelectRow={() => table.onSelectRow(row.id)}
            columns={tableHead}
          />
    );
  const activeTabData = React.useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="flex-end" gap="8px" pb={2}>
        {activeTab === 'list' ? (
          <>
            <CustomTooltip title="Refresh" arrow>
              <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
                <FontAwesome icon={faRotate} width={16} />
              </IconButton>
            </CustomTooltip>

            <ExportButton
              tooltipTitle={"Exporter"}
              type={TableType.Chauffeur}
              filteredData={dataToExport}
              tableHead={tableHead}
            />
          </>
        ) : 
          <></>
        }
        <AddButton
          onClick={handleTabAdd}
          variant="contained"
          endIcon={<FontAwesome icon={faSquarePlus} />}
        >
          Ajouter Chauffeur
        </AddButton>
      </Stack>

      <TabsCustom
        type={TableType.Chauffeur}
        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}
          sx={{ backgroundColor: 'primary.lighter' }}
          isTrajetTable={true}
        />
      ) : (
        <NewChauffeurForm
          key={activeTab}
          chauffeur={activeTabData?.content as IChauffeur}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
        
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
