'use client';

import React from 'react';
import { Box, CircularProgress, 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, 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 TableManager from '@/shared/components/table/table-manager';
import ChauffeurTableRow from './chauffeur-row';
import ChauffeurStepperForm from './chauffeur-stepper-form';
import ExportButton from '@/shared/components/table/table-export-button';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { ITripDriverAssignment, ITripDriverAssignmentDetails, ITripDriverAssignmentList } from '@/shared/types/circuit';
import { useTripDriverAssignmentTable } from './hooks/use-trip-driver-assignement-table';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import NewChauffeurForm from './driver-details';

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

export default function ChauffeurList({ circuitId,  circuitStartDate, circuitEndDate }: { circuitId: string, circuitStartDate: string, circuitEndDate: string }) {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
    markTabAsSaved,
  } = useTabsManager<ITripDriverAssignment | ITripDriverAssignmentDetails>(chauffeurTabsConfig);


  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    loading,
    totalAssignments,
    getAndViewAssignment,
    loadingDetails,
  } = useTripDriverAssignmentTable(circuitId);

  React.useEffect(() => {
    if (activeTab === 'list') {
      handleResetFilters();
    }
  }, [activeTab, handleResetFilters]);

  const renderRow = (row: ITripDriverAssignmentList) => (
    <ChauffeurTableRow
      dense={table.dense}
      key={row.id}
      row={row}
      handleDetails={() => getAndViewAssignment(row.id, handleView)}
      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>
          </>
        ) : 
          <></>
        }
        <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' ? (
        <ConditionalComponent isValid={!loadingDetails} defaultComponent={
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '300px' }}>
            <CircularProgress />
          </Box>
        }>
          <TableManager
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
            sx={{ backgroundColor: 'primary.lighter' }}
            loading={loading}
            count={totalAssignments}
            fixedHeight='calc(100vh - 350px)'
          />
        </ConditionalComponent>

      ) : (
        <ConditionalComponent isValid={activeTabData?.mode !== 'view'} defaultComponent={<NewChauffeurForm onEdit={handleEdit} />}>
          <ChauffeurStepperForm
            key={activeTab}
            chauffeur={activeTabData?.content as ITripDriverAssignment}
            mode={activeTabData?.mode || 'view'}
            onClose={(isSaved) => handleCancel(activeTab, isSaved)}
            onEdit={handleEdit}
            setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
            updateTabContent={updateTabContent}
            tabId={activeTab}
            markTabAsSaved={markTabAsSaved}
            hasUnsavedChanges={activeTabData?.hasUnsavedChanges}
            circuitId={circuitId}  
            circuitStartDate={circuitStartDate}
            circuitEndDate={circuitEndDate}  
          />
        </ConditionalComponent>
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
