/**
 * 表单设计器主组件 - 钉钉风格
 * 整合字段面板、设计画布和属性面板
 */

'use client';

import React, { useCallback, useEffect } from 'react';
import {
  DndContext,
  DragEndEvent,
  DragStartEvent,
  MouseSensor,
  TouchSensor,
  useSensor,
  useSensors,
  DragOverlay,
  pointerWithin,
} from '@dnd-kit/core';
import { arrayMove } from '@dnd-kit/sortable';
import { FieldPalette } from './FieldPalette';
import { DesignCanvas } from './DesignCanvas';
import { PropertyPanel } from './PropertyPanel';
import { useDesignerStore, useCanUndo, useCanRedo } from './useDesignerStore';
import { createField, FIELD_TYPES, type DesignField, type FieldType, type FieldTypeConfig } from './types';
import { localizeFieldConfig } from './fieldI18n';
import { useTranslation } from '@/hooks/useTranslation';

// 拖拽叠加层 - 增强视觉效果
function DragOverlayContent({ activeId, label }: { activeId: string | null; label?: string }) {
  if (!activeId) return null;

  // 从面板拖拽
  if (activeId.startsWith('palette-')) {
    const type = activeId.replace('palette-', '');
    const config = FIELD_TYPES.find((f) => f.type === type);
    if (!config) return null;

    return (
      <div className="px-5 py-3 bg-white border-2 border-blue-500 rounded-lg shadow-2xl 
        transform scale-105 animate-pulse-subtle">
        <div className="flex items-center gap-2">
          <div className="w-6 h-6 bg-blue-100 rounded flex items-center justify-center">
            <span className="text-blue-600 text-xs">+</span>
          </div>
          <span className="text-sm font-medium text-gray-800">{label || config.label}</span>
        </div>
      </div>
    );
  }

  // 从画布拖拽（排序）
  const { fields } = useDesignerStore.getState();
  const field = fields.find((f) => f.id === activeId);
  if (!field) return null;

  return (
    <div className="px-5 py-3 bg-white border-2 border-blue-500 rounded-lg shadow-2xl 
      transform scale-105">
      <div className="flex items-center gap-2">
        <div className="w-1 h-6 bg-blue-500 rounded-full" />
        <span className="text-sm font-medium text-gray-800">{field.label}</span>
      </div>
    </div>
  );
}

interface FormDesignerProps {
  initialFields?: DesignField[];
  onChange?: (fields: DesignField[]) => void;
  onSave?: (fields: DesignField[]) => void;
}

export function FormDesigner({ initialFields, onChange, onSave }: FormDesignerProps) {
  const { t } = useTranslation();
  const { fields, setFields, addField, moveField, setDragging, undo, redo } = useDesignerStore();
  const canUndo = useCanUndo();
  const canRedo = useCanRedo();
  const [activeId, setActiveId] = React.useState<string | null>(null);

  // 初始化字段
  useEffect(() => {
    if (initialFields && initialFields.length > 0) {
      setFields(initialFields);
    }
  }, [initialFields, setFields]);

  // 字段变化时通知外部
  useEffect(() => {
    onChange?.(fields);
  }, [fields, onChange]);

  // 配置拖拽传感器
  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 5,
      },
    }),
    useSensor(TouchSensor, {
      activationConstraint: {
        delay: 200,
        tolerance: 5,
      },
    })
  );

  // 开始拖拽
  const handleDragStart = useCallback((event: DragStartEvent) => {
    setActiveId(event.active.id as string);
    setDragging(true);
  }, [setDragging]);

  // 拖拽结束
  const handleDragEnd = useCallback(
    (event: DragEndEvent) => {
      const { active, over } = event;
      setActiveId(null);
      setDragging(false);

      if (!over) return;

      const activeData = active.data.current;
      const overData = over.data.current;
      const overId = over.id as string;

      // 子表单列排序由 DetailFieldDesigner 的 useDndMonitor 处理，这里跳过
      if (activeData?.type === 'detail-column') {
        return;
      }

      // 从面板拖拽到画布
      if (activeData?.type === 'palette-item') {
        const config = activeData.config as FieldTypeConfig;
        const fieldType = activeData.fieldType;
        
        // 检查是否拖拽到子表单列上（根据鼠标位置决定插入前/后）
        if (overData?.type === 'detail-column') {
          // 由 DetailFieldDesigner 的 useDndMonitor 处理
          return;
        }
        
        // 检查是否拖拽到子表单末尾
        if (overId.startsWith('detail-') && overData?.type === 'detail-drop-zone') {
          // 调用子表单的添加列方法
          const onAddColumn = overData.onAddColumn as ((type: string) => void) | undefined;
          if (onAddColumn && fieldType) {
            onAddColumn(fieldType);
          }
          return;
        }

        // 检查是否拖拽到布局容器内
        if (overData?.type === 'container-column') {
          const onAddField = overData.onAddField as ((type: FieldType) => void) | undefined;
          if (onAddField && fieldType) {
            // 检查是否支持该字段类型（不支持容器、分组和子表单嵌套）
            if (fieldType !== 'container' && fieldType !== 'detail' && fieldType !== 'group') {
              onAddField(fieldType);
            }
          }
          return;
        }

        // 检查是否拖拽到分组内（末尾添加）
        if (overData?.type === 'group-drop') {
          const onAddField = overData.onAddField as ((type: FieldType) => void) | undefined;
          if (onAddField && fieldType) {
            // 分组内支持容器和子表单，但不支持嵌套分组
            if (fieldType !== 'group') {
              onAddField(fieldType);
            }
          }
          return;
        }

        // 检查是否拖拽到分组内字段位置（任意位置插入）
        if (overData?.type === 'group-field') {
          const onInsert = overData.onInsert as ((type: FieldType, index: number) => void) | undefined;
          const index = overData.index as number;
          const getMousePosition = overData.getMousePosition as (() => 'top' | 'bottom' | null) | undefined;
          if (onInsert && fieldType && index !== undefined) {
            // 分组内支持容器和子表单，但不支持嵌套分组
            if (fieldType !== 'group') {
              // 根据鼠标位置决定插入在当前字段前还是后
              const mousePos = getMousePosition?.();
              const insertIndex = mousePos === 'bottom' ? index + 1 : index;
              onInsert(fieldType, insertIndex);
            }
          }
          return;
        }
        
        const localizedConfig = localizeFieldConfig(t, config);
        const newField = createField(localizedConfig, fields);

        // 确定插入位置
        let insertIndex = fields.length;
        if (overId !== 'design-canvas' && overId !== 'empty-canvas-drop') {
          const overIndex = fields.findIndex((f) => f.id === overId);
          if (overIndex !== -1) {
            insertIndex = overIndex;
          }
        }

        addField(newField, insertIndex);
      }
      // 画布内排序
      else if (activeData?.type === 'canvas-item') {
        const activeIndex = fields.findIndex((f) => f.id === active.id);
        const overIndex = fields.findIndex((f) => f.id === overId);

        if (activeIndex !== -1 && overIndex !== -1 && activeIndex !== overIndex) {
          moveField(activeIndex, overIndex);
        }
      }
    },
    [fields, addField, moveField, setDragging]
  );

  // 键盘快捷键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl/Cmd + Z: 撤销
      if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
        e.preventDefault();
        if (canUndo) undo();
      }
      // Ctrl/Cmd + Shift + Z 或 Ctrl/Cmd + Y: 重做
      if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) {
        e.preventDefault();
        if (canRedo) redo();
      }
      // Ctrl/Cmd + S: 保存
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        onSave?.(fields);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [canUndo, canRedo, undo, redo, onSave, fields]);

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={pointerWithin}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      <div className="flex h-full bg-gray-100">
        {/* 左侧：字段面板 */}
        <FieldPalette />

        {/* 中间：设计画布 */}
        <DesignCanvas />

        {/* 右侧：属性面板 */}
        <PropertyPanel />
      </div>

      {/* 拖拽叠加层 */}
      <DragOverlay>
        <DragOverlayContent
          activeId={activeId}
          label={
            activeId?.startsWith('palette-')
              ? (() => {
                  const type = activeId.replace('palette-', '');
                  const config = FIELD_TYPES.find((f) => f.type === type);
                  return config ? localizeFieldConfig(t, config).label : undefined;
                })()
              : undefined
          }
        />
      </DragOverlay>
    </DndContext>
  );
}
