import { useState, useEffect, useRef, useCallback } from "react";
import { client } from "@/client";
import type { AgentSessionResponse } from "@/client/models/agentSessionResponse";

/**
 * Shared hook: load and cache workspace sessions.
 * Used by both ChatSidebar and ChatList to avoid duplicate API calls.
 */
export function useWorkspaceSessions(projectName: string) {
  const [sessions, setSessions] = useState<AgentSessionResponse[]>([]);
  const [loading, setLoading] = useState(true);
  const sessionsRef = useRef<AgentSessionResponse[]>([]);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    client
      .agentListSessions()
      .then(({ data }) => {
        if (!cancelled) {
          const filtered = data.filter(
            (s) => s.enabled && s.wk != null && s.wk !== "",
          );
          sessionsRef.current = filtered;
          setSessions(filtered);
        }
      })
      .catch(() => {})
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [projectName]);

  const addSession = useCallback((session: AgentSessionResponse) => {
    setSessions((prev) => {
      const exists = prev.some((s) => s.id === session.id);
      if (exists) return prev;
      return [...prev, session];
    });
  }, []);

  return { sessions, loading, sessionsRef, addSession };
}
