/**
 * 项目-模板绑定状态管理
 * 遵循前端开发规范的状态管理设计原则
 */

import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import {
  ProjectTemplateBinding,
  ProjectTemplateBindingDetail,
  CreateProjectTemplateBindingRequest,
  UpdateProjectTemplateBindingRequest,
  ProjectTemplateBindingQueryParams,
  BindingType,
  BindingStatus,
  sortBindingsByPriority,
  filterBindings,
  getBindingStats,
} from '../types/projectTemplateBinding';
import { ProjectTemplateBindingService } from '../services/projectTemplateBindingService';

interface ProjectTemplateBindingState {
  // 数据状态
  bindings: ProjectTemplateBinding[];
  bindingDetails: ProjectTemplateBindingDetail[];
  currentBinding: ProjectTemplateBinding | null;
  
  // UI 状态
  loading: boolean;
  error: string | null;
  selectedBindingIds: string[];
  
  // 过滤和搜索状态
  filters: {
    binding_type?: BindingType;
    binding_status?: BindingStatus;
    is_active?: boolean;
    search?: string;
  };
  
  // 分页状态
  pagination: {
    page: number;
    pageSize: number;
    total: number;
  };

  // 操作方法
  actions: {
    // 数据获取
    fetchBindings: (params?: ProjectTemplateBindingQueryParams) => Promise<void>;
    fetchTemplatesByProject: (projectId: string) => Promise<void>;
    fetchProjectsByTemplate: (templateId: string) => Promise<void>;
    fetchBinding: (id: string) => Promise<void>;
    
    // 数据操作
    createBinding: (request: CreateProjectTemplateBindingRequest) => Promise<ProjectTemplateBinding>;
    updateBinding: (id: string, request: UpdateProjectTemplateBindingRequest) => Promise<ProjectTemplateBinding>;
    deleteBinding: (id: string) => Promise<void>;
    batchDeleteBindings: (ids: string[]) => Promise<void>;
    
    // 状态操作
    activateBinding: (id: string) => Promise<void>;
    deactivateBinding: (id: string) => Promise<void>;
    toggleBindingStatus: (id: string) => Promise<void>;
    setPrimaryTemplate: (projectId: string, templateId: string) => Promise<void>;
    
    // UI 操作
    setFilters: (filters: Partial<ProjectTemplateBindingState['filters']>) => void;
    clearFilters: () => void;
    setSelectedBindingIds: (ids: string[]) => void;
    clearSelection: () => void;
    setCurrentBinding: (binding: ProjectTemplateBinding | null) => void;
    
    // 分页操作
    setPage: (page: number) => void;
    setPageSize: (pageSize: number) => void;
    
    // 工具方法
    getFilteredBindings: () => ProjectTemplateBinding[];
    getSortedBindings: () => ProjectTemplateBinding[];
    getBindingStats: () => ReturnType<typeof getBindingStats>;
    
    // 错误处理
    setError: (error: string | null) => void;
    clearError: () => void;
  };
}

export const useProjectTemplateBindingStore = create<ProjectTemplateBindingState>()(
  devtools(
    (set, get) => ({
      // 初始状态
      bindings: [],
      bindingDetails: [],
      currentBinding: null,
      loading: false,
      error: null,
      selectedBindingIds: [],
      filters: {},
      pagination: {
        page: 1,
        pageSize: 20,
        total: 0,
      },

      actions: {
        // 获取绑定列表
        fetchBindings: async (params = {}) => {
          set({ loading: true, error: null });
          try {
            const bindings = await ProjectTemplateBindingService.listBindings(params);
            set({ 
              bindings: sortBindingsByPriority(bindings),
              pagination: { ...get().pagination, total: bindings.length },
              loading: false 
            });
          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '获取绑定列表失败',
              loading: false 
            });
          }
        },

        // 获取项目的模板列表
        fetchTemplatesByProject: async (projectId: string) => {
          set({ loading: true, error: null });
          try {
            const details = await ProjectTemplateBindingService.getTemplatesByProject(projectId);
            set({ 
              bindingDetails: details,
              bindings: details.map(d => d.binding),
              loading: false 
            });
          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '获取项目模板列表失败',
              loading: false 
            });
          }
        },

        // 获取模板的项目列表
        fetchProjectsByTemplate: async (templateId: string) => {
          set({ loading: true, error: null });
          try {
            const details = await ProjectTemplateBindingService.getProjectsByTemplate(templateId);
            set({ 
              bindingDetails: details,
              bindings: details.map(d => d.binding),
              loading: false 
            });
          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '获取模板项目列表失败',
              loading: false 
            });
          }
        },

        // 获取单个绑定
        fetchBinding: async (id: string) => {
          set({ loading: true, error: null });
          try {
            const binding = await ProjectTemplateBindingService.getBinding(id);
            set({ currentBinding: binding, loading: false });
          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '获取绑定详情失败',
              loading: false 
            });
          }
        },

        // 创建绑定
        createBinding: async (request: CreateProjectTemplateBindingRequest) => {
          set({ loading: true, error: null });
          try {
            const newBinding = await ProjectTemplateBindingService.createBinding(request);
            const currentBindings = get().bindings;
            set({ 
              bindings: sortBindingsByPriority([...currentBindings, newBinding]),
              loading: false 
            });
            return newBinding;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '创建绑定失败';
            set({ error: errorMessage, loading: false });
            throw new Error(errorMessage);
          }
        },

        // 更新绑定
        updateBinding: async (id: string, request: UpdateProjectTemplateBindingRequest) => {
          set({ loading: true, error: null });
          try {
            const updatedBinding = await ProjectTemplateBindingService.updateBinding(id, request);
            const currentBindings = get().bindings;
            const updatedBindings = currentBindings.map(binding => 
              binding.id === id ? updatedBinding : binding
            );
            set({ 
              bindings: sortBindingsByPriority(updatedBindings),
              currentBinding: get().currentBinding?.id === id ? updatedBinding : get().currentBinding,
              loading: false 
            });
            return updatedBinding;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '更新绑定失败';
            set({ error: errorMessage, loading: false });
            throw new Error(errorMessage);
          }
        },

        // 删除绑定
        deleteBinding: async (id: string) => {
          set({ loading: true, error: null });
          try {
            await ProjectTemplateBindingService.deleteBinding(id);
            const currentBindings = get().bindings;
            set({ 
              bindings: currentBindings.filter(binding => binding.id !== id),
              selectedBindingIds: get().selectedBindingIds.filter(selectedId => selectedId !== id),
              currentBinding: get().currentBinding?.id === id ? null : get().currentBinding,
              loading: false 
            });
          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '删除绑定失败',
              loading: false 
            });
          }
        },

        // 批量删除绑定
        batchDeleteBindings: async (ids: string[]) => {
          console.log('Store: 开始批量删除绑定, IDs:', ids);
          set({ loading: true, error: null });
          try {
            const deletedCount = await ProjectTemplateBindingService.batchDeleteBindings({ binding_ids: ids });
            console.log('Store: 批量删除成功, 删除数量:', deletedCount);

            // 清空选中状态
            set({ selectedBindingIds: [], loading: false });
          } catch (error) {
            console.error('Store: 批量删除失败:', error);
            set({
              error: error instanceof Error ? error.message : '批量删除绑定失败',
              loading: false
            });
            throw error; // 重新抛出错误以便上层处理
          }
        },

        // 激活绑定
        activateBinding: async (id: string) => {
          try {
            const updatedBinding = await ProjectTemplateBindingService.activateBinding(id);
            const currentBindings = get().bindings;
            const updatedBindings = currentBindings.map(binding => 
              binding.id === id ? updatedBinding : binding
            );
            set({ bindings: sortBindingsByPriority(updatedBindings) });
          } catch (error) {
            set({ error: error instanceof Error ? error.message : '激活绑定失败' });
          }
        },

        // 停用绑定
        deactivateBinding: async (id: string) => {
          try {
            const updatedBinding = await ProjectTemplateBindingService.deactivateBinding(id);
            const currentBindings = get().bindings;
            const updatedBindings = currentBindings.map(binding => 
              binding.id === id ? updatedBinding : binding
            );
            set({ bindings: sortBindingsByPriority(updatedBindings) });
          } catch (error) {
            set({ error: error instanceof Error ? error.message : '停用绑定失败' });
          }
        },

        // 切换绑定状态
        toggleBindingStatus: async (id: string) => {
          const binding = get().bindings.find(b => b.id === id);
          if (!binding) return;

          try {
            if (binding.is_active) {
              await get().actions.deactivateBinding(id);
            } else {
              await get().actions.activateBinding(id);
            }
          } catch (error) {
            set({ error: error instanceof Error ? error.message : '切换绑定状态失败' });
          }
        },

        // 设置主要模板
        setPrimaryTemplate: async (projectId: string, templateId: string) => {
          set({ loading: true, error: null });
          try {
            await ProjectTemplateBindingService.setPrimaryTemplate(projectId, templateId);
            // 重新获取项目的模板列表以更新状态
            await get().actions.fetchTemplatesByProject(projectId);
          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '设置主要模板失败',
              loading: false 
            });
          }
        },

        // 设置过滤器
        setFilters: (filters) => {
          set({ filters: { ...get().filters, ...filters } });
        },

        // 清除过滤器
        clearFilters: () => {
          set({ filters: {} });
        },

        // 设置选中的绑定ID
        setSelectedBindingIds: (ids) => {
          set({ selectedBindingIds: ids });
        },

        // 清除选择
        clearSelection: () => {
          set({ selectedBindingIds: [] });
        },

        // 设置当前绑定
        setCurrentBinding: (binding) => {
          set({ currentBinding: binding });
        },

        // 设置页码
        setPage: (page) => {
          set({ pagination: { ...get().pagination, page } });
        },

        // 设置页面大小
        setPageSize: (pageSize) => {
          set({ pagination: { ...get().pagination, pageSize, page: 1 } });
        },

        // 获取过滤后的绑定
        getFilteredBindings: () => {
          const { bindings, filters } = get();
          return filterBindings(bindings, filters);
        },

        // 获取排序后的绑定
        getSortedBindings: () => {
          const filteredBindings = get().actions.getFilteredBindings();
          return sortBindingsByPriority(filteredBindings);
        },

        // 获取绑定统计
        getBindingStats: () => {
          const bindings = get().bindings;
          return getBindingStats(bindings);
        },

        // 设置错误
        setError: (error) => {
          set({ error });
        },

        // 清除错误
        clearError: () => {
          set({ error: null });
        },
      },
    }),
    {
      name: 'project-template-binding-store',
    }
  )
);
