'use client';

import React from 'react';
import { useTheme } from '@mui/material/styles';
import { Box, Stack, IconButton, TableCell, Checkbox, Typography } from '@mui/material';
import { faArrowUpRightFromSquare, 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 { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
import type { IFuelHistory, ITankerType } from '@/shared/types/flottes/fuelImport';
import {
  _fuelHistories,
  DEFAULT_FUEL_CARD_TABLE_HEAD,
  DEFAULT_FUELHISTORY_TABLE_HEAD,
  INITIAL_FUELHISTORY_DATA,
} from '@/shared/_mock/flottes/_fuelImport';
import TableManager from '@/shared/components/table/table-manager';
import { dateFormat, formatDate } from '@/utils/format-time';
import { StatusChip, TrajetStyledRow } from '@/shared/sections/contract/styles';
import { type 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 { pxToRem } from '@/shared/theme/typography';
import TableActionColumn from '@/shared/components/table/table-action-column';
import FuelHistoryForm from './fuel-history-form';

const fuelHistoryTabsConfig: TabConfig<IFuelHistory> = {
  type: 'fuelHistory',
  listTitle: 'Liste carte carburant',
  newItemTitle: 'Nouvel historique de carburant',
  initialData: INITIAL_FUELHISTORY_DATA,
  getItemCode: (fuelHistory) => fuelHistory.id,
};

const TOOLTIP_TITLES = {
  edit: 'Modifier Carte Carburant',
  duplicate: 'Copier Carte Carburant',
  active: 'Carte Carburant actif',
  inactive: 'Carte Carburant inactif',
};

interface FuelHistoryListProps {
  supplierType?: ITankerType;
}

export default function FuelHistoryList({ supplierType }: FuelHistoryListProps) {
  const theme = useTheme();
  const filteredFuelHistories = React.useMemo(() => {
    if (!supplierType?.typeTanker) return _fuelHistories;
    return _fuelHistories.filter(
      (history) => history.providerType === supplierType.typeTanker
    );
  }, [supplierType?.typeTanker]);
  const fuelHistoryConfig: TableConfig<IFuelHistory> = {
    initialData: filteredFuelHistories,
    defaultTableHead: DEFAULT_FUEL_CARD_TABLE_HEAD,
  };
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
  } = useTabsManager<IFuelHistory>(fuelHistoryTabsConfig);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<IFuelHistory>(fuelHistoryConfig);

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

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

  const renderRow = (row: IFuelHistory) => {
    return (
      <TrajetStyledRow
        key={row.id}
        data-selected={table.selected.includes(row.id)}
        selected={table.selected.includes(row.id)}
        style={{ cursor: 'pointer' }}
      >
        <TableCell sx={{ py: 0 }} padding="checkbox">
          <Checkbox
            size="small"
            checked={table.selected.includes(row.id)}
            onClick={() => table.onSelectRow(row.id)}
          />
        </TableCell>

        {tableHead.slice(0, -2).map((column: any) => (
          <TableCell
            onDoubleClick={() => handleView(row)}
            key={column.id}
            align={column.align || 'left'}
            sx={{
              whiteSpace: 'nowrap',
              py: column.id === 'isActive' ? 0.2 : table.dense ? 0.5 : 1,
            }}
          >
            {renderCellContent(column.id, row[column.id as keyof IFuelHistory])}
          </TableCell>
        ))}
        <TableCell align="right" sx={{ px: 1, whiteSpace: 'nowrap' }}>
          <TableActionColumn
            handleEdit={() => handleEdit(row)}
            onToggle={(checked) => void 0}
            isActive={row.isActive}
            tooltipTitles={TOOLTIP_TITLES}
          />
        </TableCell>
      </TrajetStyledRow>
    );
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Typography
        sx={{
          fontSize: pxToRem(25),
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        {'Carte carburant'}
      </Typography>
      <Stack 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.FuelHistory}
          filteredData={dataToExport}
          tableHead={tableHead}
        />
      </Stack>
      <TabsCustom
        type="fuelHistory"
        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'}
        />
      ) : (
        <FuelHistoryForm
          fuelHistory={activeTabData?.content as IFuelHistory}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
        />
      )}
    </Box>
  );
}
