'use client';

import { useCallback, useEffect, useState } from 'react';
import type {
  AiInvocationDetail,
  AiInvocationListQuery,
  AiInvocationStats,
  ListAiInvocationsResponse,
} from '@pac/types';
import { ApiError } from '@/lib/api-client';
import { aiInvocationsApi } from './ai-invocations-api';

export type ListState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; data: ListAiInvocationsResponse; stats: AiInvocationStats | null }
  | { status: 'error'; message: string; code?: number };

export function useAiInvocationsList(initial: Partial<AiInvocationListQuery> = { page: 1, pageSize: 20 }) {
  const [query, setQueryState] = useState<Partial<AiInvocationListQuery>>(initial);
  const [state, setState] = useState<ListState>({ status: 'idle' });

  const load = useCallback(async (q: Partial<AiInvocationListQuery>) => {
    setState({ status: 'loading' });
    try {
      // stats 跟 list 并发,失败不阻断 list
      const [data, statsResult] = await Promise.allSettled([
        aiInvocationsApi.list(q),
        aiInvocationsApi.stats(),
      ]);
      if (data.status === 'rejected') throw data.reason;
      setState({
        status: 'ready',
        data: data.value,
        stats: statsResult.status === 'fulfilled' ? statsResult.value : null,
      });
    } catch (err) {
      if (err instanceof ApiError) setState({ status: 'error', message: err.message, code: err.code });
      else setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
    }
  }, []);

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

  const setQuery = useCallback((next: Partial<AiInvocationListQuery>) => {
    setQueryState((prev) => ({ ...prev, ...next, page: next.page ?? 1 }));
  }, []);
  const refresh = useCallback(() => void load(query), [load, query]);

  return { state, query, setQuery, refresh };
}

export type DetailState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; data: AiInvocationDetail }
  | { status: 'error'; message: string; code?: number };

export function useAiInvocationDetail(id: string) {
  const [state, setState] = useState<DetailState>({ status: 'idle' });

  const load = useCallback(async () => {
    setState({ status: 'loading' });
    try {
      const data = await aiInvocationsApi.detail(id);
      setState({ status: 'ready', data });
    } catch (err) {
      if (err instanceof ApiError) setState({ status: 'error', message: err.message, code: err.code });
      else setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
    }
  }, [id]);

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

  return { state, refresh: load };
}
