'use client';

import React from 'react';
import { useTheme } from '@mui/material/styles';
import { Box, Stack, IconButton, TableCell } from '@mui/material';
import { faArrowUpRightFromSquare, faRotate } from '@fortawesome/free-solid-svg-icons';
import { ActionsIconButton, iconButtonStyles, PassengerCircuitStatusChip } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { circuitStateOptions } from '@/shared/types/circuit';
import { _avenants, INITIAL_AVENANT_DATA } from '@/shared/_mock/_avenants';
import TableManager from '@/shared/components/table/table-manager';
import { dateFormat, formatDate } from '@/utils/format-time';
import { TrajetStyledRow } from '@/shared/sections/contract/styles';
import { _CIRCUIT_STATUS } from '@/shared/_mock/_circuit';
import { useRouter } from '@/hooks/use-router';
import { paths } from '@/routes/paths';
import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from '@/shared/types/common';
import { useAmendmentCircuitTable } from './hooks/use-amendment-circuit-table';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import { getLabel } from '@/shared/_mock';
import AvenantForm from './circuit-ammendment-new-view';

const avenantTabsConfig: TabConfig<AmendmentCircuit> = {
  type: 'avenant',
  listTitle: 'Liste des avenants',
  newItemTitle: 'Nouveau avenant',
  initialData: INITIAL_AVENANT_DATA,
  getItemCode: (avenant) => avenant.code,
};

export default function AvenantList({ circuitId }: { circuitId: string }) {
  const theme = useTheme();
  const router = useRouter();

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
  } = useTabsManager<AmendmentCircuit>(avenantTabsConfig);
  
  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    loading,
    totalAmendments,
  } = useAmendmentCircuitTable(circuitId);

  const activeTabData = React.useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);


  const openAvenantPage = (id:string) => {
    router.push(`${paths.dashboard.exploitation.circuitUsager.avenant}?id=${id}`);  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'startDate':
      case 'createdAt':
      case 'circuitEndDate':
        return formatDate(value, dateFormat.isoDate);
      case 'circuitState':
        return (
          <PassengerCircuitStatusChip label={getLabel(value, circuitStateOptions)} status={value} theme={theme} size="small" />
        );
      default:
        return value;
    }
  };

  const renderRow = (row: AmendmentCircuit) => {

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

        {tableHead.slice(0,-2)
          .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 AmendmentCircuit])}
            </TableCell>
          ))}
        <TableCell
          sx={{
            display: 'flex',
            gap: '4px',
            alignItems: 'center',
          }}
        >
        <CustomTooltip title={'Consulter avenant'} arrow>
          <IconButton onClick={()=> openAvenantPage(row.code)} size="small" sx={ActionsIconButton}>
            <FontAwesome icon={faArrowUpRightFromSquare} width={14} />
          </IconButton>
        </CustomTooltip>
        </TableCell>
      </TrajetStyledRow>
    );
  };

  return (
    <Box>
      <Stack
        sx={{
          visibility: activeTabData?.id === 'list' ? 'visible' : 'hidden',
        }} 
        direction="row" alignItems="center" justifyContent="flex-end" gap="8px" pb={2}>
        <CustomTooltip title="Refresh" arrow>
          <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
            <FontAwesome icon={faRotate} width={16} />
          </IconButton>
        </CustomTooltip>
        <ExportButton
          tooltipTitle={"Exporter"}
          type={TableType.Avenant}
          filteredData={dataToExport}
          tableHead={tableHead}
        />
      </Stack>
      <TabsCustom
        type="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' }}
        fixedHeight={'450px'}
        loading={loading}
        count={totalAmendments}
      />
      </>):
      (
        <AvenantForm
        circuitId={circuitId}
        avenant={activeTabData?.content as AmendmentCircuit}
        mode={activeTabData?.mode || 'view'}
        onClose={(isSaved) => handleCancel(activeTab, isSaved)}
        tabId={activeTab}
        hasBorder
        tableHead={tableHead}
      />
      )}
    </Box>
  );
}
