import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import {DEFAULT_AVENANT_TABLE_HEAD } from '@/shared/_mock/_avenants';
import { useEffect, useState, useCallback } from 'react';
import { useAmendmentStore } from '@/shared/api/stores/amendmentCiruitStore';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import { AmendmentSearchParams } from '@/shared/types/amendment';
import { enqueueSnackbar } from 'notistack';

function getDefaultParams(): AmendmentSearchParams {
  return {
    page: 0,
    size: 20,
    sortBy: 'createdAt',
    sortDirection: 'DESC',
  };
}

export function useAvenantTable() {
  const { getAllAmendments, amendments, loading, error, totalElements, exportAmendments } = useAmendmentStore();
  const [avenantData, setAvenantData] = useState<AmendmentCircuit[]>([]);
  const [params, setParams] = useState<AmendmentSearchParams>(getDefaultParams());

  const avenantConfig: TableConfig<AmendmentCircuit> = {
    initialData: avenantData,
    defaultTableHead: DEFAULT_AVENANT_TABLE_HEAD,
  };

  const tableManager = useTableManager<AmendmentCircuit>(avenantConfig);

  const mapCircuitState = useCallback((value: string) => {
    const v = value.toLowerCase();
    if ([
      'controle', 'contrôle', 'controlé', 'contrôlé', 'controlled', 'c'
    ].includes(v)) return 'CONTROLLED';
    if ([
      'non controle', 'non contrôle', 'non controlé', 'non contrôlé', 'uncontrolled', 'nc'
    ].includes(v)) return 'UNCONTROLLED';
    if ([
      'en attente', 'attente', 'on_hold', 'on hold', 'hold'
    ].includes(v)) return 'ON_HOLD';
    if ([
      'mis a jour', 'mis à jour', 'updated', 'maj'
    ].includes(v)) return 'UPDATED';
    return value;
  }, []);

  const mapActionType = useCallback((value: string) => {
    const v = value.toLowerCase();
    if ([
      'ajout passager', 'ajouter passager', 'add passenger', 'add_passenger', 'add', 'ap'
    ].includes(v)) return 'ADD_PASSENGER';
    if ([
      'suppression passager', 'supprimer passager', 'remove passenger', 'remove_passenger', 'remove', 'rp'
    ].includes(v)) return 'REMOVE_PASSENGER';
    if ([
      'changement horaire', 'modification horaire', 'schedule change', 'schedule_change', 'sc'
    ].includes(v)) return 'SCHEDULE_CHANGE';
    if ([
      'changement adresse', 'adresse utilisateur', 'user address change', 'user_address_change', 'uac'
    ].includes(v)) return 'USER_ADDRESS_CHANGE';
    return value;
  }, []);

  useEffect(() => {
    const sortDirection: 'ASC' | 'DESC' = tableManager.table.order === 'asc' ? 'ASC' : 'DESC';
    const baseParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 10,
      sortBy: tableManager.table.orderBy,
      sortDirection,
    };

    const filterParams: Record<string, any> = {};
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (value !== undefined && value !== null && value !== '') {
        if (key === 'circuitState') {
          filterParams[key] = mapCircuitState(String(value));
        } else if (key === 'type' || key === 'actionType') {
          filterParams['actionType'] = mapActionType(String(value));
        } else {
          filterParams[key] = value;
        }
      }
    });

    const newParams = { ...baseParams, ...filterParams };
    if (JSON.stringify(newParams) !== JSON.stringify(params)) {
      setParams(newParams);
    }
  }, [tableManager.table.page, tableManager.filters, tableManager.table.rowsPerPage, tableManager.table.orderBy, tableManager.table.order]);

  useEffect(() => {
    getAllAmendments(params);
  }, [params, getAllAmendments]);

  useEffect(() => {
    if (amendments && Array.isArray(amendments)) {
      setAvenantData(amendments);
    }
  }, [amendments]);

  const getExportParams = useCallback(() => {
    const exportParams: Record<string, any> = {};

    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (!value) return;
      switch (key) {
        case 'id':
          exportParams.id = value;
          break;
        case 'code':
        case 'codeAvenant':
        case 'amendmentCode':
          exportParams.code = value;
          break;
        case 'title':
        case 'intitule':
          exportParams.title = value;
          break;
        case 'amendmentObject':
        case 'objetAvenant':
          exportParams.amendmentObject = value;
          break;
        case 'circuitState':
          exportParams.circuitState = mapCircuitState(String(value));
          break;
        case 'isActive':
          exportParams.isActive = [true, 'true', 'oui', 'yes', '1'].includes((value as string).toString().toLowerCase());
          break;
        case 'startDate':
        case 'dateApplication':
          exportParams.startDate = value;
          break;
        case 'circuitEndDate':
        case 'dateFin':
          exportParams.circuitEndDate = value;
          break;
        case 'actionType':
        case 'type':
          exportParams.actionType = mapActionType(String(value));
          break;
        default:
          break;
      }
    });

    return exportParams;
  }, [tableManager.filters, mapCircuitState, mapActionType]);

  const handleExport = useCallback(async () => {
    try {
      const userIdString = localStorage.getItem('userId');
      if (!userIdString) {
        enqueueSnackbar("Utilisateur introuvable pour l'export.", { variant: 'warning' });
        return;
      }
      const userId = Number(userIdString);
      const exportParams = getExportParams();
      await exportAmendments({ ...exportParams, userId });
      enqueueSnackbar('Export des avenants lancé avec succès!', { variant: 'success' });
    } catch (error: any) {
      enqueueSnackbar(
        `Erreur lors de l\'exportation des avenants: ${error.message || 'Erreur inconnue'}`,
        { variant: 'error' }
      );
    }
  }, [exportAmendments, getExportParams]);

  return {
    ...tableManager,
    loading,
    filteredData : avenantData,
    error,
    totalElements,
    handleExport
  };
}
