"use client";

import { useCallback, useRef, useState } from "react";

import type { PriceSearchRequest, PriceSearchResponse } from "@/src/types/priceSearch";

type SearchStatus = "idle" | "loading" | "success" | "error";

export function usePriceSearch() {
  const [status, setStatus] = useState<SearchStatus>("idle");
  const [result, setResult] = useState<PriceSearchResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const abortRef = useRef<AbortController | null>(null);

  const search = useCallback(async (input: PriceSearchRequest) => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;

    setStatus("loading");
    setError(null);
    setResult(null);

    try {
      const res = await fetch("/api/articoli/ricerca-prezzi", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(input),
        signal: controller.signal,
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(
          typeof data.error === "string" ? data.error : "Errore ricerca prezzi",
        );
      }

      const response = data as PriceSearchResponse;
      setResult(response);
      setStatus("success");
      return response;
    } catch (err) {
      if (err instanceof Error && err.name === "AbortError") {
        setStatus("idle");
        return null;
      }

      const message = err instanceof Error ? err.message : "Errore sconosciuto";
      setError(message);
      setStatus("error");
      return null;
    } finally {
      if (abortRef.current === controller) {
        abortRef.current = null;
      }
    }
  }, []);

  const cancel = useCallback(() => {
    abortRef.current?.abort();
    abortRef.current = null;
    setStatus("idle");
  }, []);

  const reset = useCallback(() => {
    cancel();
    setResult(null);
    setError(null);
  }, [cancel]);

  return {
    status,
    result,
    error,
    search,
    cancel,
    reset,
    isLoading: status === "loading",
  };
}
