'use client';

import React from 'react';
import { useTheme } from '@mui/material/styles';
import { Box, Stack, IconButton, TableCell, Checkbox } from '@mui/material';
import { faArrowUpRightFromSquare, faFileExport, faRotate } from '@fortawesome/free-solid-svg-icons';
import { ActionsIconButton, 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 { IAvenant } from '@/shared/types/circuit';
import { _avenants, DEFAULT_AVENANT_CIRCUIT_TABLE_HEAD, INITIAL_AVENANT_DATA } from '@/shared/_mock/_avenants';
import TableManager from '@/shared/components/table/table-manager';
import { dateFormat, formatDate } from '@/utils/format-time';
import { StatusChip, TrajetStyledRow } from '@/shared/sections/contract/styles';
import { AntSwitch } from '@/shared/components/table/styles';
import { getEtatLabel } 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 AvenantForm from '@/shared/sections/avenant/view/avenant-new-view';
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from '@/shared/types/common';

const avenantConfig: TableConfig<IAvenant> = {
  initialData: _avenants(true),
  defaultTableHead: DEFAULT_AVENANT_CIRCUIT_TABLE_HEAD,
};

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

export default function AvenantList() {
  const theme = useTheme();
  const router = useRouter();

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
  } = useTabsManager<IAvenant>(avenantTabsConfig);
  
  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<IAvenant>(avenantConfig);
  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 'dateApplication':
      case 'dateFin':
        return formatDate(value, dateFormat.isoDate);
      case 'etat':
        return (
          <StatusChip label={getEtatLabel(value)} status={value} theme={theme} size="small" />
        );
      default:
        return value;
    }
  };

  const renderRow = (row: IAvenant) => {

    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 IAvenant])}
            </TableCell>
          ))}
        <TableCell
          sx={{
            display: 'flex',
            gap: '4px',
            alignItems: 'center',
          }}
        >
        <CustomTooltip title={'Consulter avenant'} arrow>
          <IconButton onClick={()=> openAvenantPage(row.codeAvenant)} 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'}
      />
      </>):(
        <AvenantForm
        avenant={activeTabData?.content as IAvenant}
        mode={activeTabData?.mode || 'view'}
        onClose={() => handleCancel(activeTab)}
        hasBorder
        tableHead={tableHead}
      />
      )}
    </Box>
  );
}
