import { useCallback, useEffect, useState } from 'react';
import { useSearchService } from 'src/contexts/searchContext';
import { SearchParams, SearchResult } from 'src/application/models/api/search';

export const useProductSearch = () => {
  const { searchProducts, isReady } = useSearchService();
  const [data, setData] = useState<SearchResult | undefined>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const search = useCallback(
    async (params: SearchParams) => {
      if (!isReady) {
        setError(new Error('Search service not ready - missing dependencies'));
        return;
      }

      setLoading(true);
      setError(null);

      try {
        const result = await searchProducts(params);
        setData(result);
      } catch (err) {
        setError(err instanceof Error ? err : new Error('Unknown search error'));
      } finally {
        setLoading(false);
      }
    },
    [searchProducts, isReady],
  );

  const reset = useCallback(() => {
    setData(undefined);
    setError(null);
    setLoading(false);
  }, []);

  return {
    data,
    loading,
    error,
    search,
    reset,
    isReady,
  };
};

export const useSearchWithQuery = (params: SearchParams | null) => {
  const { searchProducts, isReady } = useSearchService();
  const [data, setData] = useState<SearchResult | undefined>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const executeSearch = useCallback(
    async (searchParams: SearchParams) => {
      if (!isReady) return;

      setLoading(true);
      setError(null);

      try {
        const result = await searchProducts(searchParams);
        setData(result);
      } catch (err) {
        setError(err instanceof Error ? err : new Error('Unknown search error'));
      } finally {
        setLoading(false);
      }
    },
    [searchProducts, isReady],
  );

  useEffect(() => {
    if (params && isReady) {
      executeSearch(params);
    }
  }, [params, isReady, executeSearch]);

  const refetch = useCallback(() => {
    if (params) {
      executeSearch(params);
    }
  }, [params, executeSearch]);

  return {
    data,
    loading,
    error,
    refetch,
    isReady,
  };
};
