"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import { searchService } from "@/services/marketplace/search.service";
import type { Listing, SearchFilters } from "@/types/marketplace";
import { SEARCH_DEBOUNCE_MS } from "@/constants/marketplace";

export function useSearch(initialFilters?: Partial<SearchFilters>) {
  const [filters, setFilters] = useState<Partial<SearchFilters>>(initialFilters ?? {});
  const [results, setResults] = useState<Listing[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const doSearch = useCallback(
    async (f: Partial<SearchFilters>, p: number) => {
      setLoading(true);
      setError(null);
      try {
        const res = await searchService.search(f, p);
        setResults(res.listings);
        setTotal(res.total);
        setTotalPages(res.totalPages);
        if (f.query) searchService.saveSearch(f.query);
      } catch {
        setError("Search failed. Please try again.");
      } finally {
        setLoading(false);
      }
    },
    []
  );

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      doSearch(filters, 1);
      setPage(1);
    }, SEARCH_DEBOUNCE_MS);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [filters, doSearch]);

  const fetchSuggestions = useCallback(async (query: string) => {
    const s = await searchService.getSuggestions(query);
    setSuggestions(s);
  }, []);

  const nextPage = useCallback(() => {
    if (page < totalPages) {
      const next = page + 1;
      setPage(next);
      doSearch(filters, next);
    }
  }, [page, totalPages, filters, doSearch]);

  const prevPage = useCallback(() => {
    if (page > 1) {
      const prev = page - 1;
      setPage(prev);
      doSearch(filters, prev);
    }
  }, [page, filters, doSearch]);

  return {
    filters,
    setFilters,
    results,
    total,
    page,
    totalPages,
    loading,
    error,
    suggestions,
    fetchSuggestions,
    nextPage,
    prevPage,
  };
}
