import { useState, useCallback } from "react";
import type { SearXNGResponse, Category } from "@/lib/mock-data";

interface SearchState {
  query: string;
  results: SearXNGResponse | null;
  isLoading: boolean;
  error: string | null;
  activeCategory: Category;
  hasSearched: boolean;
}

export function useSearch() {
  const [state, setState] = useState<SearchState>({
    query: "",
    results: null,
    isLoading: false,
    error: null,
    activeCategory: "general",
    hasSearched: false,
  });

  const search = useCallback(async (query: string) => {
    if (!query.trim()) return;

    setState((prev) => ({ ...prev, query, isLoading: true, error: null, hasSearched: true }));

    try {
      const response = await fetch(`/search?format=json&q=${encodeURIComponent(query)}`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const data = await response.json();
      setState((prev) => ({
        ...prev,
        isLoading: false,
        results: data,
      }));
    } catch (err) {
      setState((prev) => ({
        ...prev,
        isLoading: false,
        error: err instanceof Error ? err.message : "Search failed",
      }));
    }
  }, []);

  const setCategory = useCallback((category: Category) => {
    setState((prev) => ({ ...prev, activeCategory: category }));
  }, []);

  const setQuery = useCallback((query: string) => {
    setState((prev) => ({ ...prev, query }));
  }, []);

  const reset = useCallback(() => {
    setState({
      query: "",
      results: null,
      isLoading: false,
      error: null,
      activeCategory: "general",
      hasSearched: false,
    });
  }, []);

  const filteredResults = state.results?.results.filter(
    (r) => state.activeCategory === "general" || r.category === state.activeCategory
  );

  return { ...state, filteredResults, search, setCategory, setQuery, reset };
}
