'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 { _chauffeurs, DEFAULT_CHAUFFEUR_TABLE_HEAD, INITIAL_TRIP_DRIVER_ASSIGNMENT_DATA } from '@/shared/_mock/_chauffeurs';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import FontAwesome from '@/shared/components/fontawesome';
import { 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';
import { ITripDriverAssignment } from '@/shared/types/circuit';

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

const chauffeurTableConfig: TableConfig<ITripDriverAssignment> = {
  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,
    markTabAsSaved,
  } = useTabsManager<ITripDriverAssignment>(chauffeurTabsConfig);


  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<ITripDriverAssignment>(chauffeurTableConfig);
   const renderRow = (row: ITripDriverAssignment) => (
       <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 ITripDriverAssignment}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={(isSaved) => handleCancel(activeTab, isSaved)}
          onEdit={handleEdit}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
          markTabAsSaved={markTabAsSaved}
          hasUnsavedChanges={activeTabData?.hasUnsavedChanges}
        />
        
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
