import { create } from 'zustand';
import type { WebCanvasWorkflow, WebUserSession } from '../types';
import type { CreatePreviewTaskInput } from '../api/webGenerationGateway';

export interface PendingAction {
  kind: 'project' | 'task';
  label: string;
  description: string;
  workflow?: WebCanvasWorkflow;
  input?: CreatePreviewTaskInput;
}

interface SessionState {
  session: WebUserSession | null;
  loginPromptOpen: boolean;
  pendingAction: PendingAction | null;
  sessionReplacedOpen: boolean;
  sessionReplacedMessage: string;
}

interface SessionActions {
  setSession: (session: WebUserSession | null) => void;
  openLoginPrompt: (action?: PendingAction) => void;
  closeLoginPrompt: () => void;
  setPendingAction: (action: PendingAction | null) => void;
  showSessionReplaced: (message?: string) => void;
  hideSessionReplaced: () => void;
  clearSession: () => void;
}

const initialState: SessionState = {
  session: null,
  loginPromptOpen: false,
  pendingAction: null,
  sessionReplacedOpen: false,
  sessionReplacedMessage: '当前账号已在其他设备登录，此设备的登录状态已失效。',
};

export const useSessionStore = create<SessionState & SessionActions>((set) => ({
  ...initialState,

  setSession: (session) => set({ session }),

  openLoginPrompt: (action) => set({
    loginPromptOpen: true,
    pendingAction: action || null,
  }),

  closeLoginPrompt: () => set({
    loginPromptOpen: false,
    pendingAction: null,
  }),

  setPendingAction: (action) => set({ pendingAction: action }),

  showSessionReplaced: (message) => set({
    sessionReplacedOpen: true,
    sessionReplacedMessage: message || '当前账号已在其他设备登录，此设备的登录状态已失效。',
  }),

  hideSessionReplaced: () => set({ sessionReplacedOpen: false }),

  clearSession: () => set({
    session: null,
    loginPromptOpen: false,
    pendingAction: null,
  }),
}));
