import { useState, useEffect, useCallback } from "react";
import { traceApi } from "../api/traceApi";
import type { TraceDetailResponse } from "../types/trace";

export const useTrace = (traceId: string | null) => {
  const [trace, setTrace] = useState<TraceDetailResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const reload = useCallback(
    async (idOverride?: string | null) => {
      const id = typeof idOverride === "string" ? idOverride : traceId;
      if (!id) return;
      setLoading(true);
      setError(null);
      try {
        const data = await traceApi.fetchTraceDetail(id);
        setTrace(data);
      } catch (err) {
        setError(err as Error);
      } finally {
        setLoading(false);
      }
    },
    [traceId],
  );

  useEffect(() => {
    void reload();
  }, [reload]);

  return { trace, loading, error, reload };
};
