'use client';

import { useCallback, useEffect, useState } from 'react';
import type { ListPlansQuery, ListPlansResponse } from '@pac/types';
import { ApiError } from '@/lib/api-client';
import { plansApi } from './plans-api';

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

export interface UsePlansList {
  state: ListState;
  query: Partial<ListPlansQuery>;
  setQuery: (next: Partial<ListPlansQuery>) => void;
  refresh: () => void;
}

const DEFAULT_QUERY: Partial<ListPlansQuery> = { view: 'mine', page: 1, pageSize: 20 };

export function usePlansList(initial: Partial<ListPlansQuery> = DEFAULT_QUERY): UsePlansList {
  const [query, setQueryState] = useState<Partial<ListPlansQuery>>(initial);
  const [state, setState] = useState<ListState>({ status: 'idle' });

  const load = useCallback(async (q: Partial<ListPlansQuery>) => {
    setState({ status: 'loading' });
    try {
      const data = await plansApi.list(q);
      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) });
      }
    }
  }, []);

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

  const setQuery = useCallback((next: Partial<ListPlansQuery>) => {
    setQueryState((prev) => {
      const merged = { ...prev, ...next, page: next.page ?? 1 };
      // 引用稳定:值没变就返回原对象,避免 [query] effect 重复 load
      // (挂载时 sort/keyword effect 用默认值 setQuery 不再触发多余请求)
      const keys = new Set([...Object.keys(prev), ...Object.keys(merged)]);
      for (const k of keys) {
        if ((prev as Record<string, unknown>)[k] !== (merged as Record<string, unknown>)[k]) {
          return merged;
        }
      }
      return prev;
    });
  }, []);

  const refresh = useCallback(() => {
    void load(query);
  }, [load, query]);

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