'use client';

import React, { useMemo } from 'react';
import { Box, Stack, IconButton, TableCell, Checkbox } from '@mui/material';
import { faArrowLeft, 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 TableManager from '@/shared/components/table/table-manager';
import { dateFormat, formatDate } from '@/utils/format-time';
import { TrajetStyledRow } from '@/shared/sections/contract/styles';
import { AmendmentPassengerDetails } from '@/shared/types/ammendment-passenger';
import {
  _avenants_usagers,
  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 { TableType } from '@/shared/types/common';
import AvenantsHorairesForm from '@/shared/sections/usager/components/usager-form/avenants-horaires/avenants-horaires-new';
import { IPassengerList } from '@/shared/types/passenger';
import { useAmendmentPassengerTable } from '@/shared/sections/usager/hooks/use-amendment-passenger-table';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { IBaseEntity } from '@/shared/types/client';
import { useAmendmentPassengerCircuitTable } from './hooks/use-amendment-passenger-circuit-table';

export interface AmendmentPassengerList extends IBaseEntity {
    observation: string;
    subject: string;
    startDate: string;
}

export interface UsagerForAmendment {
    id: string
    firstName: string
    lastName: string
  }

const avenantTabsConfig: TabConfig<AmendmentPassengerDetails> = {
  type: TableType.Avenant,
  listTitle: 'Liste des avenants',
  newItemTitle: 'Nouveau avenant',
  initialData: INITIAL_AVENANT_USAGERS_DATA,
  getItemCode: (avenant) => avenant.id,
};

interface UsagersFormProps {
  usager: UsagerForAmendment
  circuitId: string
  onBack: () => void
}

export default function AvenantsHorairesList({
  usager,
  circuitId,
  onBack
}: UsagersFormProps) {
  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    loading,
    error,
    totalAmendments,
    getAndViewAmendment
  } = useAmendmentPassengerCircuitTable(Number.parseInt(usager.id));

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    updateTabContent,
    markTabAsSaved,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    setTabReplaceCurrentTab
  } = useTabsManager<AmendmentPassengerDetails>(avenantTabsConfig);
  
  const activeTabData = React.useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);

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

  const renderRow = (row: AmendmentPassengerList) => {
    return (
      <TrajetStyledRow
        key={row.id}
        style={{ cursor: 'pointer' }}
      >
        {tableHead.map((column: any) => (
          <TableCell
            onDoubleClick={() => getAndViewAmendment(row.id, handleView)}
            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 AmendmentPassengerList])}
          </TableCell>
        ))}
      </TrajetStyledRow>
    );
  };

    return (
      <Box>
        <Box sx={{ py: 1 }}>
        <CustomTooltip title="Retour à la liste" arrow>
          <IconButton sx={iconButtonStyles} onClick={() => onBack()}>
            <FontAwesome icon={faArrowLeft} width={18} />
          </IconButton>
        </CustomTooltip>
      </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>
        </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}
            loading={loading}
            count={totalAmendments}
          />
        ) : (
          <AvenantsHorairesForm
            key={activeTabData?.id}
            usager={usager as IPassengerList}
            avenant={activeTabData?.content as AmendmentPassengerDetails}
            mode={activeTabData?.mode || 'view'}
            onClose={(isSaved) => handleCancel(activeTab, isSaved)}
            onEdit={handleEdit}
            markTabAsSaved={markTabAsSaved}
            updateTabContent={updateTabContent}
            tabId={activeTab}
            hasUnsavedChanges={activeTabData?.hasUnsavedChanges}
            setTabReplaceCurrentTab={setTabReplaceCurrentTab}
          />
        )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
      </Box>
    );
  }
