import { useEffect, useState } from "react";
import type { LineReconciliationResponse } from "@/types";

/**
 * Data hook for the ClaimDrawer's Line Reconciliation tab.
 *
 * Calls GET /api/claims/{claimId}/line-reconciliation on mount and
 * when claimId changes. When claimId is null, returns a no-data state.
 */
export function useLineReconciliation(claimId: string | null) {
  const [data, setData] = useState<LineReconciliationResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(claimId !== null);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    if (claimId === null) {
      setData(null);
      setLoading(false);
      setError(null);
      return;
    }
    let cancelled = false;
    setLoading(true);
    const baseUrl = import.meta.env.VITE_API_BASE_URL ?? "";
    fetch(`${baseUrl}/api/claims/${claimId}/line-reconciliation`)
      .then(async (r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return (await r.json()) as LineReconciliationResponse;
      })
      .then((json) => {
        if (cancelled) return;
        setData(json);
        setError(null);
      })
      .catch((e) => {
        if (cancelled) return;
        setError(e as Error);
      })
      .finally(() => {
        if (cancelled) return;
        setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [claimId]);

  return { data, loading, error };
}
