import { create } from 'zustand';
import { actionInboxApi, type ActionItem, type WorkbenchStats } from '../api/health/actionInbox';

interface WorkbenchState {
  tasks: ActionItem[];
  selectedTaskId: string | null;
  tab: 'pending' | 'completed';
  loading: boolean;
  stats: WorkbenchStats | null;

  selectTask: (id: string | null) => void;
  setTab: (tab: 'pending' | 'completed') => void;
  refreshTasks: () => Promise<void>;
  refreshStats: () => Promise<void>;
  completeTask: (id: string) => void;
}

export const useWorkbenchStore = create<WorkbenchState>((set, get) => ({
  tasks: [],
  selectedTaskId: null,
  tab: 'pending',
  loading: false,
  stats: null,

  selectTask: (id) => set({ selectedTaskId: id }),

  setTab: (tab) => {
    set({ tab, selectedTaskId: null });
    get().refreshTasks();
  },

  refreshTasks: async () => {
    set({ loading: true });
    try {
      const status = get().tab === 'pending' ? 'pending' : 'completed';
      const resp = await actionInboxApi.list({ status, page: 1, page_size: 50 });
      const tasks = Array.isArray(resp?.data) ? resp.data : [];
      set({ tasks, loading: false });
    } catch {
      set({ loading: false });
    }
  },

  refreshStats: async () => {
    try {
      const stats = await actionInboxApi.stats();
      set({ stats: stats ?? null });
    } catch { /* ignore */ }
  },

  completeTask: (id) => {
    const { tasks } = get();
    const remaining = tasks.filter(t => t.id !== id);
    const nextId = remaining.length > 0 ? remaining[0].id : null;
    set({ tasks: remaining, selectedTaskId: nextId });
    get().refreshStats();
  },
}));
