'use client';

import React from 'react';
import { useTheme } from '@mui/material/styles';
import { Box, Stack, IconButton, TableCell, Checkbox } from '@mui/material';
import {
  faArrowUpRightFromSquare,
  faPrint,
  faRotate,
  faSquarePlus,
} 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 { ICircuitContract } from '@/shared/types/circuit';
import TableManager from '@/shared/components/table/table-manager';
import {
  _circuitsContract,
  DEFAULT_CONTRACT_CIRCUIT_TABLE_HEAD,
  INITIAL_CONTRACT_CIRCUIT_DATA,
} from '@/shared/_mock/_circuit';
import { TrajetStyledRow } from '@/shared/sections/contract/styles';
import { AddButton, AntSwitch } from '@/shared/components/table/styles';
import { TableType } from '@/shared/types/common';
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 NewContratForm from './contract-new';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
const circuitConfig: TableConfig<ICircuitContract> = {
  initialData: _circuitsContract,
  defaultTableHead: DEFAULT_CONTRACT_CIRCUIT_TABLE_HEAD,
};
const contratTabsConfig: TabConfig<ICircuitContract> = {
  type: 'contrat',
  listTitle: 'Liste des contrats',
  newItemTitle: 'Nouveau contrat',
  initialData: INITIAL_CONTRACT_CIRCUIT_DATA,
  getItemCode: (contrat) => contrat.numeroContrat,
};
export default function ContratForm() {
  const theme = useTheme();
  const router = useRouter();
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<ICircuitContract>(contratTabsConfig);
  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
  } = useTableManager<ICircuitContract>(circuitConfig);
  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'numeroLot':
        return (value as string[]).join(', ');
      default:
        return value;
    }
  };
  const renderRow = (row: ICircuitContract) => {
    const openTrajetPage = (id: string) => {
      router.push(`${paths.dashboard.exploitation.contract}?id=${id}`);
    };

    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: column.id === 'numeroLot' ? 'normal' : 'nowrap', py: 1 }}
          >
            {renderCellContent(column.id, row[column.id as keyof ICircuitContract])}
          </TableCell>
        ))}
        <TableCell
          align="center"
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: 0.5,
          }}
        >
          <CustomTooltip title={'Consulter contrat'} arrow>
            <IconButton
              onClick={() => openTrajetPage(row.numeroContrat)}
              size="small"
              sx={ActionsIconButton}
            >
              <FontAwesome icon={faArrowUpRightFromSquare} width={14} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title={row.isActive ? 'Circuit actif' : 'Circuit inactif'} arrow>
            <AntSwitch theme={theme} checked={row.isActive} size="small" />
          </CustomTooltip>
        </TableCell>
      </TrajetStyledRow>
    );
  };
  const activeTabData = React.useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);
  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="flex-end" gap="8px" pb={2}>
        {activeTab === 'list' ? (
          <>
            <CustomTooltip title="Refresh" arrow>
              <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
                <FontAwesome icon={faRotate} width={16} />
              </IconButton>
            </CustomTooltip>

            <CustomTooltip title="print" arrow>
              <IconButton size="small" sx={iconButtonStyles}>
                <FontAwesome icon={faPrint} width={18} />
              </IconButton>
            </CustomTooltip>
          </>
        ) : (
          <></>
        )}
        <AddButton
          onClick={handleTabAdd}
          variant="contained"
          endIcon={<FontAwesome icon={faSquarePlus} />}
        >
          Ajouter Contrat
        </AddButton>
      </Stack>
      <TabsCustom
        type={TableType.Contrat}
        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}
        />
      ) : (
        <NewContratForm
          key={activeTab}
          contrat={activeTabData?.content as ICircuitContract}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
