import { useState, useEffect, useCallback } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { ITrajet } from '@/shared/types/trajet';
import { DEFAULT_TRAJET_TABLE_HEAD } from '@/shared/_mock/_trajets';
import { TableType } from '@/shared/types/common';
import { useTrajetStore } from '@/shared/api/stores/trajetStore';
import { EtatTrajet } from '@/shared/types/trajet';

// Define the API params type
type ApiParams = {
  id?: string;
  dateTrip?: string;
  days?: string;
  sens?: 'DEPARTURE' | 'RETURN';
  rotation?: boolean;
  nbrUsagers?: number;
  nbrEtablissements?: number;
  tripState?: 'CONTROLE' | 'MODIFIE' | 'NON CONTROLE';
  driverName?: string;
  vehicleName?: string;
  hasTolls?: boolean;
  companyName?: string;
  clientName?: string;
  tripType?: 'NORMAL' | 'PERSONALIZED';
  page: number;
  size: number;
  sortBy: string;
  sortDirection: 'asc' | 'desc';
};

const trajetConfig: TableConfig<ITrajet> = {
  type: TableType.Trajet,
  initialData: [], 
  defaultTableHead: DEFAULT_TRAJET_TABLE_HEAD,
};

export function useTrajetTable() {
  const { trajets, totalElements, loading, error, fetchTrajets, updateTrajetStatus } =
    useTrajetStore();
  const [isLoaded, setIsLoaded] = useState(false);
  const [lastParams, setLastParams] = useState<string>('');

  const tableManager = useTableManager<ITrajet>({
    ...trajetConfig,
    initialData: trajets,
  });

  const getApiParams = useCallback(() => {
    const params: ApiParams = {
      page: 0,
      size: 20,
      sortBy: 'id',
      sortDirection: 'asc' as 'asc' | 'desc',
    };

    Object.entries(tableManager.filters).forEach(([key, filter]) => {
      if (filter.value) {
        switch (key) {
          case 'id':
            params.id = filter.value;
            break;
          case 'dateDebut':
            params.dateTrip = filter.value;
            break;
          case 'days':
            params.days = filter.value;
            break;
          case 'sensAR':
            params.sens = filter.value.toLowerCase() === 'aller' ? 'DEPARTURE' : 'RETURN';
            break;
          case 'rotation':
            params.rotation = filter.value.toLowerCase() === 'oui';
            break;
          case 'nombreUsagers':
            const nbrUsagers = parseInt(filter.value);
            if (!isNaN(nbrUsagers)) {
              params.nbrUsagers = nbrUsagers;
            }

            break;
          case 'nombreEtablissements':
            params.nbrEtablissements = parseInt(filter.value);
            break;
          case 'etat':
            params.tripState = filter.value.toUpperCase() as
              | 'CONTROLE'
              | 'MODIFIE'
              | 'NON CONTROLE';
            break;
          case 'chauffeur':
            params.driverName = filter.value;
            break;
          case 'vehicule':
            params.vehicleName = filter.value;
            break;
          case 'peages':
            params.hasTolls = filter.value.toLowerCase() === 'oui';
            break;
          case 'societe':
            params.companyName = filter.value;
            break;
          case 'client':
            params.clientName = filter.value;
            break;
          case 'typeTrajet':
            params.tripType = filter.value.toLowerCase() === 'normal' ? 'NORMAL' : 'PERSONALIZED';
            break;
        }
      }
    });

    return params;
  }, [tableManager.filters]);

  useEffect(() => {
    const params = getApiParams();
    const paramsString = JSON.stringify(params);

    if (paramsString !== lastParams) {
      setLastParams(paramsString);
      fetchTrajets(params);
    }
  }, [fetchTrajets, getApiParams, lastParams]);

  const handleStatusChange = useCallback(
    async (row: ITrajet, newStatus: string, field: keyof ITrajet) => {
      try {
        let backendField: string;
        switch (field) {
          case 'typeTrajet':
            backendField = 'tripType';
            break;
          case 'etat':
            backendField = 'tripState';
            break;
          case 'rotation':
          case 'peages':
            backendField = field;
            break;
          default:
            backendField = field;
        }

        await updateTrajetStatus(row.id, backendField, newStatus);

        const currentParams = getApiParams();
        fetchTrajets(currentParams);
      } catch (error) {
        console.error('Error updating status:', error);
      }
    },
    [updateTrajetStatus, fetchTrajets, getApiParams]
  );

  return {
    ...tableManager,
    filteredData: trajets,
    totalElements,
    loading,
    error,
    handleStatusChange,
    dataToExport: trajets,
  };
}
