/**
 * 表单设计器状态管理
 * 支持撤销/重做、复制等高级操作
 */

import { create } from 'zustand';
import type { DesignField, DesignerState, DesignerActions } from './types';
import { generateId, generateFieldName } from './types';

interface DesignerStore extends DesignerState, DesignerActions {}

const MAX_HISTORY = 50;

export const useDesignerStore = create<DesignerStore>((set, get) => ({
  // 初始状态
  fields: [],
  selectedFieldId: null,
  isDragging: false,
  history: [[]],
  historyIndex: 0,

  // 保存历史记录（用于撤销/重做）
  _saveHistory: (fields: DesignField[]) => {
    const { history, historyIndex } = get();
    const newHistory = history.slice(0, historyIndex + 1);
    newHistory.push(fields);
    if (newHistory.length > MAX_HISTORY) {
      newHistory.shift();
    }
    return {
      history: newHistory,
      historyIndex: newHistory.length - 1,
    };
  },

  // Actions
  addField: (field, index) =>
    set((state) => {
      const newFields = [...state.fields];
      if (index !== undefined && index >= 0 && index <= newFields.length) {
        newFields.splice(index, 0, field);
      } else {
        newFields.push(field);
      }
      return {
        fields: newFields,
        selectedFieldId: field.id,
        ...(get() as any)._saveHistory(newFields),
      };
    }),

  updateField: (id, updates) =>
    set((state) => {
      const newFields = state.fields.map((f) => {
        if (f.id === id) {
          // ✅ 深度合并，确保嵌套对象（如 children）创建新引用
          const updated = { ...f, ...updates };
          // ✅ 如果更新了 children，确保是新数组
          if (updates.children) {
            updated.children = [...updates.children];
          }
          return updated;
        }
        return f;
      });
      return {
        fields: newFields,
        ...(get() as any)._saveHistory(newFields),
      };
    }),

  removeField: (id) =>
    set((state) => {
      const newFields = state.fields.filter((f) => f.id !== id);
      return {
        fields: newFields,
        selectedFieldId: state.selectedFieldId === id ? null : state.selectedFieldId,
        ...(get() as any)._saveHistory(newFields),
      };
    }),

  moveField: (fromIndex, toIndex) =>
    set((state) => {
      const newFields = [...state.fields];
      const [removed] = newFields.splice(fromIndex, 1);
      newFields.splice(toIndex, 0, removed);
      return {
        fields: newFields,
        ...(get() as any)._saveHistory(newFields),
      };
    }),

  duplicateField: (id) =>
    set((state) => {
      const fieldIndex = state.fields.findIndex((f) => f.id === id);
      if (fieldIndex === -1) return state;

      const sourceField = state.fields[fieldIndex];
      
      // 使用标准命名规则生成新的组件标识（与新建组件相同的逻辑）
      const newName = generateFieldName(sourceField.type, state.fields);
      
      // 创建副本
      const newField: DesignField = {
        ...sourceField,
        id: generateId(),
        name: newName,
        label: sourceField.label, // 保持原标题，不加"副本"后缀
        options: sourceField.options ? [...sourceField.options] : undefined,
        validation: sourceField.validation ? { ...sourceField.validation } : undefined,
      };

      const newFields = [...state.fields];
      newFields.splice(fieldIndex + 1, 0, newField);

      return {
        fields: newFields,
        selectedFieldId: newField.id,
        ...(get() as any)._saveHistory(newFields),
      };
    }),

  selectField: (id) => {
    console.log('✅ selectField 调用:', { id });
    set({ selectedFieldId: id });
  },

  setDragging: (isDragging) =>
    set({ isDragging }),

  setFields: (fields) =>
    set((state) => ({
      fields,
      selectedFieldId: null,
      ...(get() as any)._saveHistory(fields),
    })),

  undo: () =>
    set((state) => {
      if (state.historyIndex <= 0) return state;
      const newIndex = state.historyIndex - 1;
      return {
        fields: [...state.history[newIndex]],
        historyIndex: newIndex,
        selectedFieldId: null,
      };
    }),

  redo: () =>
    set((state) => {
      if (state.historyIndex >= state.history.length - 1) return state;
      const newIndex = state.historyIndex + 1;
      return {
        fields: [...state.history[newIndex]],
        historyIndex: newIndex,
        selectedFieldId: null,
      };
    }),

  reset: () =>
    set({
      fields: [],
      selectedFieldId: null,
      isDragging: false,
      history: [[]],
      historyIndex: 0,
    }),
}));

// 辅助 hooks
export function useCanUndo() {
  return useDesignerStore((state) => state.historyIndex > 0);
}

export function useCanRedo() {
  return useDesignerStore((state) => state.historyIndex < state.history.length - 1);
}
