import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableType } from '@/shared/types/common';
import { DEFAULT_USAGER_TABLE_HEAD } from '@/shared/_mock/_usagers';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { useEffect, useState } from 'react';
import { IPassengerList, SearchPassengerParams } from '@/shared/types/passenger';
import { isValidFilterValue } from '@/utils/helper';

export function useUsagerTable() {
  const [params, setParams] = useState<SearchPassengerParams>({
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDir: 'DESC'
  });

  const { passengers, totalElements, loading, error, searchPassengers } = usePassengerStore();
  
  const passengerConfig: TableConfig<IPassengerList> = {
    type: TableType.Usager,
    initialData: passengers || [],
    defaultTableHead: DEFAULT_USAGER_TABLE_HEAD,
  };

  const tableManager = useTableManager<IPassengerList>(passengerConfig);

  useEffect(() => {
    const baseParams: SearchPassengerParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'id',
      sortDir: tableManager.table.order?.toUpperCase() as 'ASC' | 'DESC'
    };

    const filterParams: Record<string, string | number> = {};
    
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (key === 'id' && isValidFilterValue(value)) {
          filterParams[key] = Number(value);
      } else if (isValidFilterValue(value)) {
        filterParams[key] = value;
      }
    });

    const newParams: SearchPassengerParams = {
      ...baseParams,
      ...filterParams
    };

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

  useEffect(() => {
    searchPassengers(params);
  }, [params, searchPassengers]);
  
  return {
    ...tableManager,
    loading,
    error,
    totalPassengers: totalElements || 0
  };
}