import { create } from 'zustand';
import type { WebProjectSummary, WebCanvasWorkflow } from '../types';
import { createBlankWorkflow } from '../data/workflows';

interface ProjectState {
  projects: WebProjectSummary[];
  projectsLoaded: boolean;
  canvasWorkflow: WebCanvasWorkflow;
  currentCanvasProjectId: string | null;
  pendingDeleteProject: WebProjectSummary | null;
  deleteProjectSubmitting: boolean;
}

interface ProjectActions {
  setProjects: (projects: WebProjectSummary[]) => void;
  setProjectsLoaded: (loaded: boolean) => void;
  setCanvasWorkflow: (workflow: WebCanvasWorkflow) => void;
  setCurrentCanvasProjectId: (id: string | null) => void;
  openDeleteProject: (project: WebProjectSummary) => void;
  closeDeleteProject: () => void;
  setDeleteProjectSubmitting: (submitting: boolean) => void;
  clearProjectState: () => void;
}

const initialState: ProjectState = {
  projects: [],
  projectsLoaded: false,
  canvasWorkflow: createBlankWorkflow(),
  currentCanvasProjectId: null,
  pendingDeleteProject: null,
  deleteProjectSubmitting: false,
};

export const useProjectStore = create<ProjectState & ProjectActions>((set) => ({
  ...initialState,

  setProjects: (projects) => set({ projects }),

  setProjectsLoaded: (loaded) => set({ projectsLoaded: loaded }),

  setCanvasWorkflow: (workflow) => set({ canvasWorkflow: workflow }),

  setCurrentCanvasProjectId: (id) => set({ currentCanvasProjectId: id }),

  openDeleteProject: (project) => set({ pendingDeleteProject: project }),

  closeDeleteProject: () => set({
    pendingDeleteProject: null,
    deleteProjectSubmitting: false,
  }),

  setDeleteProjectSubmitting: (submitting) => set({ deleteProjectSubmitting: submitting }),

  clearProjectState: () => set(initialState),
}));
