'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 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 './avenants-horaires-new';
import { IPassengerList } from '@/shared/types/passenger';
import { useAmendmentPassengerTable } from '@/shared/sections/usager/hooks/use-amendment-passenger-table';
import { AmendmentPassengerList } from '@/shared/types/ammendment-passenger';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';


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: IPassengerList
}

export default function AvenantsHorairesList({
  usager,
}: UsagersFormProps) {
  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    loading,
    error,
    totalAmendments,
    getAndViewAmendment
  } = useAmendmentPassengerTable(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>
        <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 disabled={!usager?.id} 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}
            loading={loading}
            count={totalAmendments}
          />
        ) : (
          <AvenantsHorairesForm
            key={activeTabData?.id}
            usager={usager}
            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>
    );
  }
