import { useCallback, useMemo, useRef } from 'react';
import { debounce } from '@mui/material';
import { enqueueSnackbar } from 'notistack';
import { useEstablishmentStore } from '@/shared/api/stores/admin-service/establishmentStore';

export const useEstablishmentSearch = () => {
  const { searchWithSpecificInfo, searchWithSpecificInfoLoading } = useEstablishmentStore();
  const abortControllerRef = useRef<AbortController | null>(null);

  const searchEstablishmentsRaw = useCallback(
    async (query?: string) => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }

      abortControllerRef.current = new AbortController();
      const signal = abortControllerRef.current.signal;

      try {
        if (!query || query.trim() === '') {
          await searchWithSpecificInfo(undefined, undefined, signal);
        } else {
          const trimmedQuery = query.trim();
          const isNumericId = /^\d+$/.test(trimmedQuery);
          
          if (isNumericId) {
            await searchWithSpecificInfo(undefined, trimmedQuery, signal);
          } else {
            await searchWithSpecificInfo(trimmedQuery, undefined, signal);
          }
        }
      } catch (error: any) {
        if (error.name !== "CanceledError" && error.code !== "ERR_CANCELED") {
          console.error("Erreur lors de la recherche des établissements", { variant: "error" });
        }
      }
    },
    [searchWithSpecificInfo],
  );

  const searchEstablishments = useMemo(
    () => debounce(searchEstablishmentsRaw, 300),
    [searchEstablishmentsRaw]
  );

  return {
    searchEstablishments,
    isLoading: searchWithSpecificInfoLoading,
  };
};
