import { useCallback } from "preact/hooks";
import { streamSseResponse } from "../../lib/sse";
import type { CardMessageMetadata, SessionSummary } from "../../types";
import type { RawPersistedCard, RawWorkbenchItem, SessionDetailResponse } from "./types";

export const BACKEND_URL = import.meta.env.VITE_BACKEND_URL ?? "";

export function useBackendActions({
  onMessage,
  suppressRtcTextRef,
  getActiveSessionId,
  setTextStreaming,
}: {
  onMessage: (raw: string) => void;
  suppressRtcTextRef: { current: number };
  getActiveSessionId: () => string;
  setTextStreaming: (value: boolean) => void;
}) {
  const sendTextMessage = useCallback(
    async (text: string, metadata?: CardMessageMetadata) => {
      const message = text.trim();
      if (!message) return;
      suppressRtcTextRef.current += 1;
      setTextStreaming(true);
      try {
        const url = BACKEND_URL ? `${BACKEND_URL}/message/stream` : "/message/stream";
        const resp = await fetch(url, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            text: message,
            metadata: metadata ?? {},
            chat_id: getActiveSessionId(),
          }),
        });
        if (!resp.ok) throw new Error(`Send failed (${resp.status})`);
        await streamSseResponse(resp, onMessage);
      } finally {
        setTextStreaming(false);
        suppressRtcTextRef.current = Math.max(0, suppressRtcTextRef.current - 1);
      }
    },
    [getActiveSessionId, onMessage, setTextStreaming, suppressRtcTextRef],
  );

  return { sendTextMessage };
}

export async function fetchPersistedCardsFromBackend(
  chatId: string,
): Promise<RawPersistedCard[] | null> {
  const params = new URLSearchParams({ chat_id: chatId });
  const url = BACKEND_URL ? `${BACKEND_URL}/cards?${params}` : `/cards?${params}`;
  const resp = await fetch(url, { cache: "no-store" });
  if (!resp.ok) {
    console.warn(`[cards] /cards returned ${resp.status}`);
    return null;
  }
  return (await resp.json()) as RawPersistedCard[];
}

export async function fetchWorkbenchFromBackend(
  chatId: string,
): Promise<RawWorkbenchItem[] | null> {
  const params = new URLSearchParams({ chat_id: chatId });
  const url = BACKEND_URL ? `${BACKEND_URL}/workbench?${params}` : `/workbench?${params}`;
  const resp = await fetch(url, { cache: "no-store" });
  if (!resp.ok) {
    console.warn(`[workbench] /workbench returned ${resp.status}`);
    return null;
  }
  const payload = (await resp.json()) as { items?: RawWorkbenchItem[] };
  return Array.isArray(payload.items) ? payload.items : null;
}

export async function fetchSessionsFromBackend(): Promise<SessionSummary[] | null> {
  const url = BACKEND_URL ? `${BACKEND_URL}/sessions` : "/sessions";
  const resp = await fetch(url, { cache: "no-store" });
  if (!resp.ok) {
    console.warn(`[sessions] /sessions returned ${resp.status}`);
    return null;
  }
  const payload = (await resp.json()) as { sessions?: SessionSummary[] };
  return Array.isArray(payload.sessions) ? payload.sessions : null;
}

export async function fetchSessionDetailFromBackend(
  chatId: string,
): Promise<SessionDetailResponse | null> {
  const url = BACKEND_URL ? `${BACKEND_URL}/sessions/${chatId}` : `/sessions/${chatId}`;
  const resp = await fetch(url, { cache: "no-store" });
  if (!resp.ok) {
    console.warn(`[sessions] /sessions/${chatId} returned ${resp.status}`);
    return null;
  }
  return (await resp.json()) as SessionDetailResponse;
}

export async function createSessionInBackend(title = ""): Promise<SessionSummary | null> {
  const url = BACKEND_URL ? `${BACKEND_URL}/sessions` : "/sessions";
  const resp = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });
  if (!resp.ok) {
    console.warn(`[sessions] POST /sessions returned ${resp.status}`);
    return null;
  }
  const payload = (await resp.json()) as { session?: SessionSummary };
  return payload.session ?? null;
}

export async function renameSessionInBackend(
  chatId: string,
  title: string,
): Promise<SessionSummary | null> {
  const url = BACKEND_URL ? `${BACKEND_URL}/sessions/${chatId}` : `/sessions/${chatId}`;
  const resp = await fetch(url, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });
  if (!resp.ok) {
    console.warn(`[sessions] PATCH /sessions/${chatId} returned ${resp.status}`);
    return null;
  }
  const payload = (await resp.json()) as { session?: SessionSummary };
  return payload.session ?? null;
}

export async function deleteSessionInBackend(chatId: string): Promise<boolean> {
  const url = BACKEND_URL ? `${BACKEND_URL}/sessions/${chatId}` : `/sessions/${chatId}`;
  const resp = await fetch(url, { method: "DELETE" });
  if (!resp.ok) {
    console.warn(`[sessions] DELETE /sessions/${chatId} returned ${resp.status}`);
    return false;
  }
  return true;
}
