import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';
import { Project, CreateProjectRequest, UpdateProjectRequest } from '../types/project';

/**
 * 项目状态管理
 * 遵循 Tauri 开发规范的状态管理模式
 */
interface ProjectState {
  // 状态
  projects: Project[];
  currentProject: Project | null;
  isLoading: boolean;
  error: string | null;

  // 操作
  loadProjects: () => Promise<void>;
  createProject: (request: CreateProjectRequest) => Promise<void>;
  updateProject: (id: string, request: UpdateProjectRequest) => Promise<void>;
  deleteProject: (id: string) => Promise<void>;
  setCurrentProject: (project: Project | null) => void;
  clearError: () => void;
  
  // 工具方法
  validateProjectPath: (path: string) => Promise<boolean>;
  getDefaultProjectName: (path: string) => Promise<string>;
}

export const useProjectStore = create<ProjectState>((set, get) => ({
  // 初始状态
  projects: [],
  currentProject: null,
  isLoading: false,
  error: null,

  // 加载所有项目
  loadProjects: async () => {
    set({ isLoading: true, error: null });
    try {
      const projects = await invoke<Project[]>('get_all_projects');
      set({ projects, isLoading: false });
    } catch (error) {
      set({ 
        error: error as string, 
        isLoading: false,
        projects: []
      });
    }
  },

  // 创建项目
  createProject: async (request: CreateProjectRequest) => {
    set({ isLoading: true, error: null });
    try {
      const newProject = await invoke<Project>('create_project', { request });
      const { projects } = get();
      set({ 
        projects: [newProject, ...projects],
        isLoading: false 
      });
    } catch (error) {
      set({ error: error as string, isLoading: false });
      throw error;
    }
  },

  // 更新项目
  updateProject: async (id: string, request: UpdateProjectRequest) => {
    set({ isLoading: true, error: null });
    try {
      const updatedProject = await invoke<Project>('update_project', { id, request });
      const { projects } = get();
      const updatedProjects = projects.map(p => 
        p.id === id ? updatedProject : p
      );
      set({ 
        projects: updatedProjects,
        currentProject: get().currentProject?.id === id ? updatedProject : get().currentProject,
        isLoading: false 
      });
    } catch (error) {
      set({ error: error as string, isLoading: false });
      throw error;
    }
  },

  // 删除项目
  deleteProject: async (id: string) => {
    set({ isLoading: true, error: null });
    try {
      await invoke('delete_project', { id });
      const { projects, currentProject } = get();
      const filteredProjects = projects.filter(p => p.id !== id);
      set({ 
        projects: filteredProjects,
        currentProject: currentProject?.id === id ? null : currentProject,
        isLoading: false 
      });
    } catch (error) {
      set({ error: error as string, isLoading: false });
      throw error;
    }
  },

  // 设置当前项目
  setCurrentProject: (project: Project | null) => {
    set({ currentProject: project });
  },

  // 清除错误
  clearError: () => {
    set({ error: null });
  },

  // 验证项目路径
  validateProjectPath: async (path: string): Promise<boolean> => {
    try {
      return await invoke<boolean>('validate_project_path', { path });
    } catch (error) {
      console.error('验证路径失败:', error);
      return false;
    }
  },

  // 获取默认项目名称
  getDefaultProjectName: async (path: string): Promise<string> => {
    try {
      return await invoke<string>('get_default_project_name', { path });
    } catch (error) {
      console.error('获取默认项目名称失败:', error);
      return '';
    }
  },
}));
