/**
 * 中间设计画布
 * 可拖放字段的区域
 */

import React from 'react';
import { useDroppable } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { Empty, Typography, Button, Tooltip } from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import FieldItem from './FieldItem';
import type { FieldConfig } from '../types';
import '../styles.css';

const { Text } = Typography;

interface DesignCanvasProps {
  fields: FieldConfig[];
  selectedFieldId?: string;
  onSelectField: (fieldId: string) => void;
  onCopyField: (fieldId: string) => void;
  onPasteToCanvas: () => void;
  onPasteToGrid: (gridId: string, colIndex: number) => void;
  onDeleteField: (fieldId: string) => void;
  labelAlign?: 'left' | 'right' | 'top';
  hasClipboard?: boolean;
  activeId?: string | null; // 正在拖拽的元素ID
  overId?: string | null; // 拖拽悬停的目标ID
  duplicateFieldIds?: Set<string>; // 冲突的字段ID集合
}

const DesignCanvas: React.FC<DesignCanvasProps> = ({
  fields,
  selectedFieldId,
  onSelectField,
  onCopyField,
  onPasteToCanvas,
  onPasteToGrid,
  onDeleteField,
  labelAlign = 'right',
  hasClipboard = false,
  activeId,
  overId,
  duplicateFieldIds = new Set(),
}) => {
  const { setNodeRef } = useDroppable({
    id: 'canvas',
    data: {
      accept: 'field',
    },
  });

  return (
    <div className="form-designer-canvas">
      <div className="form-designer-canvas-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Text strong style={{ fontSize: 16 }}>表单设计</Text>
          <Tooltip 
            title={
              <div style={{ fontSize: 12 }}>
                <div><kbd style={{ padding: '2px 6px', background: '#fff', color: '#333', borderRadius: 3, border: '1px solid #d9d9d9' }}>Ctrl/Cmd+C</kbd> 复制选中字段</div>
                <div style={{ marginTop: 4 }}><kbd style={{ padding: '2px 6px', background: '#fff', color: '#333', borderRadius: 3, border: '1px solid #d9d9d9' }}>Ctrl/Cmd+V</kbd> 粘贴到画布</div>
                <div style={{ marginTop: 4 }}><kbd style={{ padding: '2px 6px', background: '#fff', color: '#333', borderRadius: 3, border: '1px solid #d9d9d9' }}>Delete</kbd> 删除选中字段</div>
              </div>
            }
          >
            <InfoCircleOutlined style={{ fontSize: 14, color: '#8c8c8c', cursor: 'help' }} />
          </Tooltip>
        </div>
        {hasClipboard && (
          <Button 
            type="dashed" 
            size="small" 
            icon={<PlusOutlined />}
            onClick={onPasteToCanvas}
          >
            粘贴 <kbd style={{ fontSize: 10, opacity: 0.6 }}>Ctrl+V</kbd>
          </Button>
        )}
      </div>

      <div 
        ref={setNodeRef}
        className="form-designer-canvas-body"
      >
        {fields.length === 0 ? (
          <div className="form-designer-canvas-empty">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="从左侧拖拽组件到此处开始设计表单"
            />
          </div>
        ) : (
          <SortableContext
            items={fields.map(f => f.id)}
            strategy={verticalListSortingStrategy}
          >
            <div className="form-designer-field-list">
              {fields.map((field) => (
                <React.Fragment key={field.id}>
                  {/* 插入指示器 - 显示在字段上方（栅格字段会根据边界自动判断） */}
                  {activeId && 
                   overId === field.id && 
                   activeId !== field.id && 
                   !overId?.toString().includes('-col-') && (
                    <DropIndicator text={field.type === 'grid' ? "释放以插入到栅格前/后" : "释放以插入到此处"} />
                  )}
                  
                  <FieldItem
                    field={field}
                    isSelected={field.id === selectedFieldId}
                    onSelect={() => onSelectField(field.id)}
                    onCopy={() => onCopyField(field.id)}
                    onDelete={() => onDeleteField(field.id)}
                    selectedFieldId={selectedFieldId}
                    onSelectField={onSelectField}
                    onCopyField={onCopyField}
                    onPasteToGrid={onPasteToGrid}
                    onDeleteField={onDeleteField}
                    labelAlign={labelAlign}
                    hasClipboard={hasClipboard}
                    hasDuplicateName={duplicateFieldIds.has(field.id)}
                  />
                </React.Fragment>
              ))}
              <CanvasBottomDropZone />
            </div>
          </SortableContext>
        )}
      </div>
    </div>
  );
};

// 插入指示器组件
interface DropIndicatorProps {
  text: string;
}

const DropIndicator: React.FC<DropIndicatorProps> = ({ text }) => {
  return (
    <div
      style={{
        height: 40,
        margin: '8px 0',
        border: '2px dashed #1890ff',
        borderRadius: 6,
        background: 'linear-gradient(90deg, #f0f5ff 0%, #e6f4ff 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#1890ff',
        fontSize: 13,
        fontWeight: 500,
        transition: 'all 0.2s ease',
        animation: 'dropIndicatorPulse 1.5s ease-in-out infinite',
      }}
    >
      {text}
    </div>
  );
};

// 画布底部拖放区域组件
const CanvasBottomDropZone: React.FC = () => {
  const { setNodeRef, isOver } = useDroppable({
    id: 'canvas-bottom',
    data: {
      accept: 'field',
      isBottom: true, // 标识这是底部区域
    },
  });

  return (
    <div
      ref={setNodeRef}
      style={{
        minHeight: 60,
        marginTop: 16,
        border: `2px dashed ${isOver ? '#1890ff' : 'transparent'}`,
        borderRadius: 6,
        background: isOver ? '#f0f5ff' : 'transparent',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: isOver ? '#1890ff' : '#d9d9d9',
        fontSize: 12,
        transition: 'all 0.3s ease',
      }}
    >
      {isOver ? '释放以添加到底部' : '拖拽到此处添加到底部'}
    </div>
  );
};

export default DesignCanvas;

