  'use client';

  import React, { useMemo } from 'react';
  import { Box, Stack, IconButton, TableCell, Checkbox } from '@mui/material';
  import { faPlusCircle, faRotate } from '@fortawesome/free-solid-svg-icons';
  import { iconButtonStyles } from '@/shared/theme/css';
  import FontAwesome from '@/shared/components/fontawesome';
  import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
  import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
  import TableManager from '@/shared/components/table/table-manager';
  import { dateFormat, formatDate } from '@/utils/format-time';
  import { TrajetStyledRow } from '@/shared/sections/contract/styles';
  import { IAvenantUsager } from '@/shared/types/usager';
  import {
    _avenants_usagers,
    DEFAULT_AVENANT_USAGERS_TABLE_HEAD,
    INITIAL_AVENANT_USAGERS_DATA,
  } from '@/shared/_mock/_avenantUsager';
  import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
  import TabsCustom from '@/shared/components/tabs/tabs-custom';
  import { ModeType, TableType } from '@/shared/types/common';
  import AvenantsHorairesForm from './avenants-horaires-new';
import { IPassengerList } from '@/shared/types/passenger';


  const avenantchauffeurTabsConfig: TabConfig<IAvenantUsager> = {
    type: 'avenants',
    listTitle: 'Liste des avenants',
    newItemTitle: 'Nouveau avenants',
    initialData: INITIAL_AVENANT_USAGERS_DATA,
    getItemCode: (avenant) => avenant.numeroAvenant,
  };

  interface UsagersFormProps {
    usager: IPassengerList;
  }

  export default function AvenantsHorairesList({
    usager,
  }: UsagersFormProps) {
    const initialAvenants = useMemo(() => {
      return usager.email ? _avenants_usagers : [] 
    }, [usager.email])
  
    const circuitConfig: TableConfig<IAvenantUsager> = {
      initialData: initialAvenants,
      defaultTableHead: DEFAULT_AVENANT_USAGERS_TABLE_HEAD,
    }
    const {
      table,
      filteredData,
      filters,
      tableHead,
      notFound,
      handleFilterChange,
      handleResetFilters,
      handleResetColumns,
      handleColumnsChange,
      handleSave,
    } = useTableManager<IAvenantUsager>(circuitConfig);
    const {
      tabs,
      activeTab,
      handleTabClose,
      handleTabChange,
      handleTabAdd,
      handleEdit,
      handleView,
      handleCancel,
    } = useTabsManager<IAvenantUsager>(avenantchauffeurTabsConfig);
    
    const activeTabData = React.useMemo(() => {
      return tabs.find((tab) => tab.id === activeTab);
    }, [tabs, activeTab]);

    const renderCellContent = (columnId: string, value: any) => {
      switch (columnId) {
        case 'dateApplication':
          return formatDate(value, dateFormat.isoDate);
        default:
          return value;
      }
    };

    const renderRow = (row: IAvenantUsager) => {
      return (
        <TrajetStyledRow
          key={row.id}
          style={{ cursor: 'pointer' }}
        >

          {tableHead.map((column: any) => (
            <TableCell
              onDoubleClick={() => handleView(row)}
              key={column.id}
              align={column.align || 'left'}
              sx={{ whiteSpace: 'nowrap', py: column.id === 'etat' ? 0.2 : table.dense ? 0.5 : 1 }}
            >
              {renderCellContent(column.id, row[column.id as keyof IAvenantUsager])}
            </TableCell>
          ))}
        </TrajetStyledRow>
      );
    };

    return (
      <Box>
        <Stack direction="row" alignItems="center" justifyContent="flex-end" gap="8px" pb={2}>
          <CustomTooltip title="Refresh" arrow>
            <IconButton
              onClick={handleResetFilters}
              sx={{ ...iconButtonStyles, visibility: activeTab === 'list' ? 'visible' : 'hidden' }}
            >
              <FontAwesome icon={faRotate} width={16} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title="Ajouter Avenant" arrow>
            <IconButton sx={{ ...iconButtonStyles }} onClick={handleTabAdd}>
              <FontAwesome icon={faPlusCircle} width={18} />
            </IconButton>
          </CustomTooltip>
        </Stack>
        <TabsCustom
          type={TableType.Avenant}
          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}
          />
        ) : (
          <AvenantsHorairesForm
            key={activeTabData?.id}
            usager={usager}
            avenant={activeTabData?.content as IAvenantUsager}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={() => handleCancel(activeTab)}
            onEdit={handleEdit}
          />
        )}
      </Box>
    );
  }
