import { useCallback } from "react";
import { useClaimsStore } from "@/stores/claims";
import * as claimsService from "@/services/claims";

export function useClaims() {
  const {
    claims,
    inputText,
    extraction,
    setInputText,
    setClaims,
    setExtraction,
    clearAll,
  } = useClaimsStore();

  const extract = useCallback(async () => {
    if (!inputText.trim()) return;

    setExtraction({ status: "extracting", error: null });

    try {
      const extracted = await claimsService.extractClaims(inputText);
      setExtraction({ status: "checking" });

      const checked = await claimsService.checkClaims(extracted);
      setClaims(checked);
      setExtraction({ status: "idle" });
    } catch (error) {
      const message =
        error instanceof Error ? error.message : "Extraction failed";
      setExtraction({ status: "error", error: message });
    }
  }, [inputText, setExtraction, setClaims]);

  const save = useCallback(async (): Promise<boolean> => {
    if (claims.length === 0) return false;

    const toSave = claims.map((c) => c.claim);

    try {
      await claimsService.saveClaims(toSave);
      clearAll();
      return true;
    } catch (error) {
      const message =
        error instanceof Error ? error.message : "Failed to save claims";
      setExtraction({ status: "error", error: message });
      return false;
    }
  }, [claims, clearAll, setExtraction]);

  return {
    claims,
    inputText,
    extraction,
    setInputText,
    extract,
    save,
    clear: clearAll,
    isLoading:
      extraction.status === "extracting" || extraction.status === "checking",
  };
}
