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 { enqueueSnackbar } from 'notistack';
import { useTripCircuitStore } from '@/shared/api/stores/circuit-service/tripCircuitStore';
import { TripCircuitDetails, TripDTO, TripListParams, CircuitState, TripType, SensTrip } from '@/shared/types/circuit';

type ApiParams = TripListParams;

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

export function useTrajetTable() {
  const { getAllTrips, tripList, tripListTotalElements, loading, error, exportTrips } = useTripCircuitStore();
  const { getTripCircuitById } = useTripCircuitStore();
  const [lastParams, setLastParams] = useState<string>('');
  const [params, setParams] = useState<ApiParams>({
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'ASC',
  });

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

  // Écouter les changements de pagination du tableManager
  useEffect(() => {
    if (tableManager.table.rowsPerPage > 0) {
      setParams(prev => ({
        ...prev,
        page: tableManager.table.page,
        size: tableManager.table.rowsPerPage,
      }));
    }
  }, [tableManager.table.page, tableManager.table.rowsPerPage]);

  const getApiParams = useCallback(() => {
    const baseParams: ApiParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'id',
      sortDirection: (tableManager.table.order || 'ASC').toUpperCase() as 'ASC' | 'DESC',
    };

    Object.entries(tableManager.filters).forEach(([key, filter]) => {
      if (filter.value) {
        switch (key) {
          case 'id':
            baseParams.id = filter.value;
            break;
          case 'startDate':
            baseParams.startDate = filter.value;
            break;
          case 'createdAt':
            baseParams.createdAt = filter.value;
            break;
          case 'tripTitle':
            baseParams.title = filter.value;
            break;
          case 'tripDirection':
            const tripDirectionValue = filter.value.toLowerCase();
            if (['aller', 'depart', 'départ', 'a', 'd'].includes(tripDirectionValue)) {
              baseParams.tripDirection = SensTrip.DEPARTURE;
            } else if (['retour', 'return', 'r', 'ret'].includes(tripDirectionValue)) {
              baseParams.tripDirection = SensTrip.RETURN;
            }
            break;
          case 'isRotation':
            const rotationValue = filter.value.toLowerCase();
            baseParams.isRotation = ['oui', 'yes', 'true', 'vrai', '1', 'rotation'].includes(rotationValue);
            break;
          case 'numberOfPassengers':
            const nbrPassengers = parseInt(filter.value);
            if (!isNaN(nbrPassengers)) {
            }
            break;
          case 'numberOfEstablishments':
            const nbrEstablishments = parseInt(filter.value);
            if (!isNaN(nbrEstablishments)) {
            }
            break;
          case 'circuitState':
            break;
          case 'hasTolls':
            const tollsValue = filter.value.toLowerCase();
            baseParams.hasTolls = ['oui', 'yes', 'true', 'vrai', '1', 'péage', 'peage'].includes(tollsValue);
            break;
          case 'agencyName':
            break;
          case 'client':
            break;
          case 'tripType':
            const tripTypeValue = filter.value.toLowerCase();
            if (['normal', 'trajet normal'].includes(tripTypeValue)) {
              baseParams.tripType = TripType.NORMAL;
            } else if (['personnalisé', 'personnalise', 'trajet personnalisé' , 'trajet personnalise'].includes(tripTypeValue)) {
              baseParams.tripType = TripType.PERSONALIZED;
            }
            break;
        }
      }
    });

    return baseParams;
  }, [tableManager.filters, tableManager.table.page, tableManager.table.rowsPerPage, tableManager.table.orderBy, tableManager.table.order]);

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

    if (paramsString !== lastParams) {
      setLastParams(paramsString);
      getAllTrips(newParams);
    }
  }, [getAllTrips, getApiParams, lastParams]);

  const handleStatusChange = useCallback(
    async (row: TripDTO, newStatus: string, field: keyof TripDTO) => {
      try {
        console.log('Status change:', row.id, field, newStatus);

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

  const getTripCircuit = useCallback(
    async (id: string, handleView: (details: TripCircuitDetails) => void) => {
      try {
        const details = await getTripCircuitById(id);
        if (details) {
          handleView(details);
        }

      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la récupération du détail', { variant: 'error' });
      }
    },
    [getTripCircuitById]
  );

  const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setParams(prev => ({
      ...prev,
      page: newPage
    }));
  };

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const size = parseInt(event.target.value, 10);
    if (!isNaN(size) && size > 0) {
      setParams(prev => ({
        ...prev,
        size,
        page: 0
      }));
    }
  };

  const handleExport = useCallback(async () => {
    try {
      const userIdString = localStorage.getItem('userId');
      if (userIdString) {
        const userId = Number(userIdString);

        const baseParams = getApiParams();

        const exportParams: any = {
          userId,
        };

        if (baseParams.id) exportParams.id = baseParams.id;
        if (baseParams.startDate) exportParams.startDate = baseParams.startDate;
        if (baseParams.title) exportParams.title = baseParams.title;
        if (baseParams.tripDirection) exportParams.tripDirection = baseParams.tripDirection;
        if (baseParams.isRotation !== undefined) exportParams.isRotation = baseParams.isRotation;
        if (baseParams.hasTolls !== undefined) exportParams.hasTolls = baseParams.hasTolls;
        if (baseParams.tripType) exportParams.tripType = baseParams.tripType;

        await exportTrips(exportParams);
        enqueueSnackbar('Export des trajets lancé avec succès!', { variant: 'success' });
      }
    } catch (error: any) {
      enqueueSnackbar(
        `Erreur lors de l'exportation des trajets: ${error.message || 'Erreur inconnue'}`,
        { variant: 'error' }
      );
    }
  }, [exportTrips, getApiParams]);

  return {
    ...tableManager,
    filteredData: tripList,
    totalElements: tripListTotalElements,
    loading,
    error,
    handleStatusChange,
    dataToExport: tripList,
    getTripCircuit,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    handleExport,
  };
}
