'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) => ({ ...prev, ...next, page: next.page ?? 1 }));
  }, []);

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

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