/**
 * 子表单字段设计器组件
 * 钉钉风格的子表单（明细表）设计
 * 从左侧控件库拖拽添加列，支持列排序
 */

'use client';

import React, { useState, useCallback, useEffect } from 'react';
import { useDroppable, useDndContext, useDndMonitor } from '@dnd-kit/core';
import {
  SortableContext,
  horizontalListSortingStrategy,
  useSortable,
  arrayMove,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import {
  Plus,
  Trash2,
  GripVertical,
  Settings,
  ChevronDown,
  ChevronUp,
  Table,
  Calendar,
  ChevronDownIcon,
  User,
  CheckSquare,
  Maximize2,
  Upload,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useTranslation } from '@/hooks/useTranslation';
import type { DesignField, FieldType } from './types';
import { generateId, generateFieldName, FIELD_TYPES } from './types';
import { localizeFieldConfig } from './fieldI18n';
import { useDesignerStore } from './useDesignerStore';

// 子表单支持的字段类型（不包括 detail，不支持嵌套）
const DETAIL_SUPPORTED_TYPES: FieldType[] = [
  'text',
  'textarea',
  'number',
  'select',
  'multiSelect',
  'radio',
  'checkbox',
  'date',
  'dateRange',
  'member',
  'department',
  'image',
  'file',
];

interface DetailFieldDesignerProps {
  field: DesignField;
  onChange: (updates: Partial<DesignField>) => void;
  isSelected: boolean;
  onSelect: () => void;
}

export function DetailFieldDesigner({
  field,
  onChange,
  isSelected,
  onSelect,
}: DetailFieldDesignerProps) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(true);
  const [editingColumn, setEditingColumn] = useState<DesignField | null>(null);

  const columns = field.children || [];
  
  // ✅ 引入 store 来选中列和获取全局字段
  const { selectField: selectFieldInStore, fields: allFields } = useDesignerStore();

  // 添加列（支持在指定位置插入）
  const handleAddColumn = useCallback((fieldType: FieldType, insertIndex?: number) => {
    const config = FIELD_TYPES.find((f) => f.type === fieldType);
    if (!config || !DETAIL_SUPPORTED_TYPES.includes(fieldType)) return;
    const localizedConfig = localizeFieldConfig(t, config);

    // ✅ 使用全局字段生成器，确保名称全局唯一且按类型递增
    const fieldName = generateFieldName(fieldType, allFields);

    const newColumn: DesignField = {
      id: generateId(),
      type: fieldType,
      name: fieldName,
      label: localizedConfig.label,
      width: '1/3',
      ...localizedConfig.defaultProps,
    };

    if (insertIndex !== undefined && insertIndex >= 0) {
      const newColumns = [...columns];
      newColumns.splice(insertIndex, 0, newColumn);
      onChange({ children: newColumns });
    } else {
      onChange({ children: [...columns, newColumn] });
    }
  }, [columns, onChange, allFields, t]);

  // 删除列
  const handleDeleteColumn = (columnId: string) => {
    onChange({
      children: columns.filter((c) => c.id !== columnId),
    });
  };

  // 更新列
  const handleUpdateColumn = (columnId: string, updates: Partial<DesignField>) => {
    onChange({
      children: columns.map((c) =>
        c.id === columnId ? { ...c, ...updates } : c
      ),
    });
  };

  // 移动列（排序）
  const handleMoveColumn = useCallback((activeId: string, overId: string) => {
    const oldIndex = columns.findIndex((c) => c.id === activeId);
    const newIndex = columns.findIndex((c) => c.id === overId);
    if (oldIndex >= 0 && newIndex >= 0 && oldIndex !== newIndex) {
      onChange({ children: arrayMove(columns, oldIndex, newIndex) });
    }
  }, [columns, onChange]);

  // 监听拖拽事件，处理子表单内的列排序和从面板拖入
  useDndMonitor({
    onDragEnd(event) {
      const { active, over } = event;
      if (!over) return;
      
      const activeId = active.id as string;
      const overId = over.id as string;
      const activeData = active.data.current;
      const overData = over.data.current;
      
      // 检查是否是子表单内部的列排序
      const isActiveColumn = columns.some((c) => c.id === activeId);
      const isOverColumn = columns.some((c) => c.id === overId);
      
      if (isActiveColumn && isOverColumn && activeId !== overId) {
        handleMoveColumn(activeId, overId);
        return;
      }
      
      // 检查是否是从面板拖入到子表单列上
      if (activeData?.type === 'palette-item' && overData?.type === 'detail-column') {
        // 确保是拖到当前子表单的列上
        if (overData.fieldId !== field.id) return;
        
        const fieldType = activeData.fieldType as FieldType;
        if (!fieldType || !DETAIL_SUPPORTED_TYPES.includes(fieldType)) return;
        
        const columnIndex = overData.index as number;
        const getMousePosition = overData.getMousePosition as (() => 'left' | 'right' | null) | undefined;
        const mousePos = getMousePosition?.();
        
        // 根据鼠标位置决定插入位置
        if (mousePos === 'left') {
          handleAddColumn(fieldType, columnIndex);
        } else {
          handleAddColumn(fieldType, columnIndex + 1);
        }
      }
    },
  });

  return (
    <div
      className="transition-all bg-white"
      onClick={(e) => {
        e.stopPropagation();
        onSelect();
      }}
    >
      {/* 子表单标题 */}
      <div className="mb-2">
        <span className="text-sm font-medium text-gray-700">
          {field.label}
        </span>
        {field.required && <span className="text-red-500 ml-1">*</span>}
      </div>

      {/* 子表单内容 */}
      {expanded && (
        <>
          {columns.length === 0 ? (
            // 空状态 - 放置区
            <DetailDropZone
              fieldId={field.id}
              zoneId="main"
              onAddColumn={handleAddColumn}
            />
          ) : (
            // 表格预览 - 钉钉风格，支持横向滚动，列为整体（表头+数据）
            <div className="border border-gray-200 rounded-lg overflow-hidden">
              <div className="flex">
                {/* 序号列 - 固定左侧 */}
                <div className="w-10 flex-shrink-0 flex flex-col sticky left-0 z-10 border-r border-gray-200 bg-white">
                  {/* 表头 */}
                  <div className="h-10 flex items-center justify-center bg-gray-50 border-b border-gray-200">
                    <Maximize2 className="w-3.5 h-3.5 text-gray-400" />
                  </div>
                  {/* 数据 */}
                  <div className="flex-1 flex items-center justify-center bg-white text-sm text-gray-500 py-3">
                    1
                  </div>
                </div>
                
                {/* 数据列区域 - 可滚动 */}
                <div className="flex-1 overflow-x-auto">
                  <div className="flex min-w-full">
                    <SortableContext items={columns.map((c) => c.id)} strategy={horizontalListSortingStrategy}>
                      {columns.map((col, index) => (
                        <SortableColumn
                          key={`${col.id}-${col.label}-${col.required}-${col.placeholder || ''}`}
                          column={col}
                          index={index}
                          totalColumns={columns.length}
                          fieldId={field.id}
                          onSelectColumn={() => {
                            selectFieldInStore(col.id);
                          }}
                          onEdit={() => setEditingColumn(col)}
                          onDelete={() => handleDeleteColumn(col.id)}
                          onInsertBefore={(type) => handleAddColumn(type, index)}
                          onInsertAfter={(type) => handleAddColumn(type, index + 1)}
                        />
                      ))}
                    </SortableContext>
                  </div>
                </div>
                
                {/* 操作列 - 固定右侧 */}
                <div className="w-14 flex-shrink-0 flex flex-col sticky right-0 z-10 border-l border-gray-200 shadow-[-2px_0_4px_rgba(0,0,0,0.05)] bg-white">
                  {/* 表头 */}
                  <div className="h-10 flex items-center justify-center bg-gray-50 border-b border-gray-200">
                    <span className="text-xs text-gray-500">{t.forms.designer.detail.actions.tableActions}</span>
                  </div>
                  {/* 数据 */}
                  <div className="flex-1 flex items-center justify-center bg-white">
                    <span className="text-xs text-gray-400 cursor-pointer hover:text-red-500">{t.forms.common.delete}</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 底部操作栏 */}
          <div className="flex items-center gap-2 mt-2">
            <button className="flex items-center gap-1 px-2 py-1 text-xs text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors">
              <Plus className="w-3 h-3" />
              {t.forms.designer.detail.actions.addItem}
            </button>
            <button className="flex items-center gap-1 px-2 py-1 text-xs text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors">
              <Upload className="w-3 h-3" />
              {t.forms.designer.detail.actions.batchImport}
            </button>
          </div>
        </>
      )}

      {/* 编辑列对话框 */}
      <Dialog open={!!editingColumn} onOpenChange={(open) => !open && setEditingColumn(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{t.forms.designer.detail.dialog.editColumnTitle}</DialogTitle>
          </DialogHeader>
          {editingColumn && (
            <ColumnEditor
              column={editingColumn}
              onChange={(updates) => {
                handleUpdateColumn(editingColumn.id, updates);
                setEditingColumn({ ...editingColumn, ...updates });
              }}
              onClose={() => setEditingColumn(null)}
              t={t}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

// 子表单放置区 - 使用外部 DndContext
function DetailDropZone({ 
  fieldId,
  zoneId,
  onAddColumn, 
  compact = false,
  isHeader = false,
  isDataRow = false,
  isFooter = false,
}: { 
  fieldId: string;
  zoneId: string;
  onAddColumn: (fieldType: FieldType) => void;
  compact?: boolean;
  isHeader?: boolean;
  isDataRow?: boolean;
  isFooter?: boolean;
}) {
  const { t } = useTranslation();
  // 使用唯一的 droppable ID，包含 detail 前缀以便识别
  const droppableId = `detail-${fieldId}-${zoneId}`;
  const { setNodeRef, isOver, active } = useDroppable({ 
    id: droppableId,
    data: {
      type: 'detail-drop-zone',
      fieldId,
      onAddColumn,
    }
  });

  // 检查拖拽的是否是支持的字段类型
  const activeData = active?.data?.current;
  const draggedFieldType = activeData?.fieldType as FieldType | undefined;
  const isFromPalette = activeData?.type === 'palette-item';
  const isValidDrop = isFromPalette && draggedFieldType && DETAIL_SUPPORTED_TYPES.includes(draggedFieldType);
  const isNestedDetail = draggedFieldType === 'detail';
  const isContainer = draggedFieldType === 'container';

  if (compact) {
    // 紧凑模式 - 蓝色竖条指示器
    return (
      <div
        ref={setNodeRef}
        className={`
          w-8 flex-shrink-0 flex items-center justify-center cursor-pointer
          transition-all duration-200
          ${isOver && isValidDrop 
            ? 'bg-blue-50' 
            : isOver && (isNestedDetail || isContainer)
            ? 'bg-red-50'
            : 'hover:bg-gray-50'
          }
        `}
      >
        {/* 蓝色竖条指示器 */}
        <div 
          className={`
            w-1 h-full transition-all duration-200
            ${isOver && isValidDrop 
              ? 'bg-blue-500 shadow-[0_0_8px_rgba(59,130,246,0.5)]' 
              : isOver && (isNestedDetail || isContainer)
              ? 'bg-red-400'
              : 'bg-gray-200'
            }
          `}
        />
      </div>
    );
  }

  return (
    <div
      ref={setNodeRef}
      className={`
        border-2 border-dashed rounded-lg p-8 text-center
        transition-all duration-300
        ${isOver && isValidDrop 
          ? 'border-blue-500 bg-blue-50 shadow-[inset_0_0_20px_rgba(59,130,246,0.15)]' 
          : isOver && (isNestedDetail || isContainer)
          ? 'border-red-400 bg-red-50 shadow-[inset_0_0_20px_rgba(239,68,68,0.15)]'
          : 'border-gray-300 bg-gray-50/50 hover:border-gray-400 hover:bg-gray-50'
        }
      `}
    >
      {isOver && (isNestedDetail || isContainer) ? (
        <div className="animate-pulse">
          <div className="w-12 h-12 mx-auto mb-3 bg-red-100 rounded-full flex items-center justify-center">
            <span className="text-red-500 text-xl">✕</span>
          </div>
          <div className="text-red-500 text-sm font-medium mb-1">{t.forms.designer.detail.dropzone.invalidTitle}</div>
          <p className="text-xs text-red-400">{t.forms.designer.detail.dropzone.invalidDesc}</p>
        </div>
      ) : isOver && isValidDrop ? (
        <div className="animate-pulse">
          <div className="w-14 h-14 mx-auto mb-3 bg-blue-100 rounded-full flex items-center justify-center ring-4 ring-blue-200">
            <Plus className="w-7 h-7 text-blue-600" />
          </div>
          <div className="text-blue-600 text-sm font-medium mb-1">{t.forms.designer.detail.dropzone.validTitle}</div>
          <p className="text-xs text-blue-400">{t.forms.designer.detail.dropzone.validDesc}</p>
        </div>
      ) : (
        <>
          <div className="w-12 h-12 mx-auto mb-3 bg-gray-100 rounded-full flex items-center justify-center">
            <Table className="w-6 h-6 text-gray-400" />
          </div>
          <div className="text-gray-500 text-sm mb-1">{t.forms.designer.detail.dropzone.idleTitle}</div>
          <p className="text-xs text-gray-400">{t.forms.designer.detail.dropzone.idleDesc}</p>
        </>
      )}
    </div>
  );
}

// 可排序的列（表头+数据作为整体，根据鼠标位置显示左/右侧插入指示器）
function SortableColumn({
  column,
  index,
  totalColumns,
  fieldId,
  onSelectColumn,
  onEdit,
  onDelete,
  onInsertBefore,
  onInsertAfter,
}: {
  column: DesignField;
  index: number;
  totalColumns: number;
  fieldId: string;
  onSelectColumn: () => void;
  onEdit: () => void;
  onDelete: () => void;
  onInsertBefore: (fieldType: FieldType) => void;
  onInsertAfter: (fieldType: FieldType) => void;
}) {
  const { t } = useTranslation();
  const columnRef = React.useRef<HTMLDivElement>(null);
  const [mousePosition, setMousePosition] = React.useState<'left' | 'right' | null>(null);

  // 用于存储最新的鼠标位置，供 data 使用
  const mousePositionRef = React.useRef<'left' | 'right' | null>(null);
  mousePositionRef.current = mousePosition;

  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
    over,
  } = useSortable({ 
    id: column.id,
    data: {
      type: 'detail-column',
      fieldId,
      column,
      index,
      getMousePosition: () => mousePositionRef.current,
      onInsertBefore,
      onInsertAfter,
    },
  });

  // 获取当前拖拽上下文
  const { active, over: globalOver } = useDndContext();
  
  // 检查全局 over 是否指向当前列
  const isGlobalOverThis = globalOver?.id === column.id;

  // 实际的 isOver 状态
  const isActuallyOver = isGlobalOverThis;

  // 监听鼠标移动，判断在列的左半边还是右半边
  React.useEffect(() => {
    if (!isActuallyOver || !columnRef.current) {
      setMousePosition(null);
      return;
    }

    const updateMousePosition = (clientX: number) => {
      if (!columnRef.current) return;
      const rect = columnRef.current.getBoundingClientRect();
      const midX = rect.left + rect.width / 2;
      setMousePosition(clientX < midX ? 'left' : 'right');
    };

    const handleMouseMove = (e: MouseEvent) => {
      updateMousePosition(e.clientX);
    };

    // 立即获取当前鼠标位置
    const initPosition = () => {
      const rect = columnRef.current?.getBoundingClientRect();
      if (rect) {
        setMousePosition('right');
      }
    };
    requestAnimationFrame(initPosition);

    document.addEventListener('mousemove', handleMouseMove);
    return () => document.removeEventListener('mousemove', handleMouseMove);
  }, [isActuallyOver]);
  
  // 合并 refs
  const combinedRef = React.useCallback((node: HTMLDivElement | null) => {
    setNodeRef(node);
    (columnRef as React.MutableRefObject<HTMLDivElement | null>).current = node;
  }, [setNodeRef]);

  // 优化 transform，只使用 translate，不使用 scale
  const style: React.CSSProperties = {
    transform: transform ? `translate3d(${transform.x}px, ${transform.y}px, 0)` : undefined,
    transition: isDragging ? undefined : transition,
    zIndex: isDragging ? 100 : undefined,
  };

  // 获取全局拖拽上下文中的 active 数据
  const activeData = active?.data?.current;
  const draggedFieldType = activeData?.fieldType as FieldType | undefined;
  const isFromPalette = activeData?.type === 'palette-item';
  const isValidPaletteDrop = isFromPalette && draggedFieldType && DETAIL_SUPPORTED_TYPES.includes(draggedFieldType);
  const isNestedDetail = draggedFieldType === 'detail';
  const isContainer = draggedFieldType === 'container';
  const isInvalidDrop = isFromPalette && (isNestedDetail || isContainer);

  // 检查是否有子表单列正在排序并 hover 到此列
  const isColumnSorting = activeData?.type === 'detail-column' && activeData?.fieldId === fieldId;
  const isOverThisColumn = over?.id === column.id && active?.id !== column.id;
  
  // 判断是否显示指示器
  // 1. 从面板拖入有效组件时
  // 2. 从面板拖入无效组件时（显示红色）
  // 3. 子表单内部排序时
  const showPaletteIndicator = isActuallyOver && isFromPalette;
  const showSortIndicator = isColumnSorting && isOverThisColumn;
  const showIndicator = showPaletteIndicator || showSortIndicator;
  const indicatorColor = isInvalidDrop ? 'bg-red-400' : 'bg-blue-500 shadow-[0_0_8px_rgba(59,130,246,0.5)]';

  // 所有列都使用 flex-1 自适应宽度，设置最小宽度确保内容可见
  // 当列总宽度超过容器时，flex-shrink-0 防止压缩，触发横向滚动
  const widthClass = 'flex-1 min-w-[120px] flex-shrink-0';

  return (
    <div
      ref={combinedRef}
      style={style}
      onClick={(e) => {
        // ✅ 阻止事件冒泡到子表单容器
        e.stopPropagation();
        // ✅ 选中列，在右侧 PropertyPanel 显示列的编辑界面
        onSelectColumn();
      }}
      className={`
        ${widthClass} flex flex-col border-r border-gray-200 relative hover:bg-blue-50/30 transition-colors cursor-pointer
        ${isDragging ? 'opacity-50 shadow-lg' : ''}
      `}
    >
      {/* 左侧插入指示器 */}
      {showIndicator && mousePosition === 'left' && (
        <div className={`absolute left-0 top-0 bottom-0 w-1 z-30 ${indicatorColor}`} />
      )}
      
      {/* 右侧插入指示器 */}
      {showIndicator && mousePosition === 'right' && (
        <div className={`absolute right-0 top-0 bottom-0 w-1 z-30 ${indicatorColor}`} />
      )}
      
      {/* 表头 - 整个表头可拖拽 */}
      <div 
        {...attributes} 
        {...listeners}
        className={`
          h-10 px-3 flex items-center bg-gray-50 border-b border-gray-200 
          cursor-grab active:cursor-grabbing select-none
        `}
      >
        <div className="flex items-center gap-2 group w-full">
          <GripVertical className="w-4 h-4 text-gray-300 flex-shrink-0" />
          <span className="text-sm text-gray-900 flex-1 truncate">
            {column.label}
            {column.required && <span className="text-red-500 ml-0.5">*</span>}
          </span>
          <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <button
              onClick={(e) => {
                e.stopPropagation();
                onEdit();
              }}
              className="p-1 hover:bg-gray-100 rounded transition-colors"
              title={t.forms.designer.detail.column.edit}
            >
              <Settings className="w-3.5 h-3.5 text-gray-400" />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onDelete();
              }}
              className="p-1 hover:bg-red-50 rounded transition-colors"
              title={t.forms.designer.detail.column.delete}
            >
              <Trash2 className="w-3.5 h-3.5 text-gray-400 hover:text-red-500" />
            </button>
          </div>
        </div>
      </div>
      
      {/* 数据行 - 高度自适应 */}
      <div className="flex-1 px-3 py-3 bg-white">
        <ColumnPreview column={column} />
      </div>
    </div>
  );
}

// 列预览 - 子表单内组件
function ColumnPreview({ column }: { column: DesignField }) {
  const { t } = useTranslation();
  const inputClass = "w-full h-9 px-3 border border-gray-200 rounded text-sm text-gray-900 bg-white placeholder:text-gray-400 focus:outline-none focus:border-blue-400";

  switch (column.type) {
    case 'text':
      return (
        <input 
          type="text" 
          value={column.defaultValue as string || ''} 
          placeholder={column.placeholder || t.forms.designer.detail.placeholders.input} 
          className={inputClass} 
          readOnly 
        />
      );
    case 'textarea':
      return (
        <textarea 
          value={column.defaultValue as string || ''} 
          placeholder={column.placeholder || t.forms.designer.detail.placeholders.textarea} 
          className={`${inputClass} h-24 py-2 resize-none`} 
          readOnly 
        />
      );
    case 'number':
      return (
        <input 
          type="text" 
          value={column.defaultValue !== undefined ? String(column.defaultValue) : ''} 
          placeholder={column.placeholder || t.forms.designer.detail.placeholders.number} 
          className={inputClass} 
          readOnly 
        />
      );
    case 'select':
    case 'multiSelect':
      // ✅ 优先显示默认值，无默认值时显示提示文字
      const selectDisplayText = column.defaultValue 
        ? (column.options?.find(opt => opt.value === column.defaultValue)?.label || String(column.defaultValue))
        : (column.placeholder || t.forms.designer.detail.placeholders.select);
      const hasSelectValue = !!column.defaultValue;
      return (
        <div className={`${inputClass} flex items-center cursor-pointer`}>
          <span className={hasSelectValue ? "text-gray-900 flex-1" : "text-gray-400 flex-1"}>
            {selectDisplayText}
          </span>
          <ChevronDownIcon className="w-3 h-3 text-gray-400" />
        </div>
      );
    case 'radio':
      return (
        <div className="flex items-center gap-2">
          {(column.options || [{ label: t.forms.designer.defaults.optionLabel.replace('{index}', '1'), value: '1' }]).slice(0, 2).map((opt, idx) => (
            <label key={opt.value} className="flex items-center gap-1 text-xs text-gray-700">
              <div className={`w-3 h-3 rounded-full border-2 ${idx === 0 ? 'border-blue-500' : 'border-gray-300'}`}>
                {idx === 0 && <div className="w-full h-full rounded-full bg-blue-500 scale-50" />}
              </div>
              {opt.label}
            </label>
          ))}
        </div>
      );
    case 'checkbox':
      return (
        <div className="flex items-center gap-2">
          {(column.options || [{ label: t.forms.designer.defaults.optionLabel.replace('{index}', '1'), value: '1' }]).slice(0, 2).map((opt, idx) => (
            <label key={opt.value} className="flex items-center gap-1 text-xs text-gray-700">
              <div className={`w-3 h-3 rounded border-2 flex items-center justify-center ${idx === 0 ? 'border-blue-500 bg-blue-500' : 'border-gray-300'}`}>
                {idx === 0 && <CheckSquare className="w-2 h-2 text-white" />}
              </div>
              {opt.label}
            </label>
          ))}
        </div>
      );
    case 'date':
    case 'dateRange':
      // ✅ 优先显示默认值，无默认值时显示提示文字
      const dateDisplayText = column.defaultValue 
        ? String(column.defaultValue)
        : (column.placeholder || t.forms.designer.detail.placeholders.date);
      const hasDateValue = !!column.defaultValue;
      return (
        <div className={`${inputClass} flex items-center cursor-pointer`}>
          <span className={hasDateValue ? "text-gray-900 flex-1" : "text-gray-400 flex-1"}>
            {dateDisplayText}
          </span>
          <Calendar className="w-3 h-3 text-gray-400" />
        </div>
      );
    case 'member':
      // ✅ 优先显示默认值，无默认值时显示提示文字
      const memberDisplayText = column.defaultValue 
        ? String(column.defaultValue)
        : (column.placeholder || t.forms.designer.detail.placeholders.member);
      const hasMemberValue = !!column.defaultValue;
      return (
        <div className={`${inputClass} flex items-center gap-1.5 cursor-pointer`}>
          <div className="w-4 h-4 rounded-full bg-blue-100 flex items-center justify-center">
            <User className="w-2.5 h-2.5 text-blue-600" />
          </div>
          <span className={hasMemberValue ? "text-gray-900" : "text-gray-400"}>
            {memberDisplayText}
          </span>
        </div>
      );
    case 'department':
      // ✅ 优先显示默认值，无默认值时显示提示文字
      const deptDisplayText = column.defaultValue 
        ? String(column.defaultValue)
        : (column.placeholder || t.forms.designer.detail.placeholders.department);
      const hasDeptValue = !!column.defaultValue;
      return (
        <div className={`${inputClass} flex items-center gap-1.5 cursor-pointer`}>
          <User className="w-3 h-3 text-gray-400" />
          <span className={hasDeptValue ? "text-gray-900" : "text-gray-400"}>
            {deptDisplayText}
          </span>
        </div>
      );
    case 'image':
    case 'file':
      return (
        <div className="h-7 border border-dashed border-gray-300 rounded flex items-center justify-center text-xs text-gray-400 cursor-pointer hover:border-blue-400 hover:text-blue-500">
          {t.forms.designer.detail.placeholders.upload}
        </div>
      );
    default:
      return <input type="text" placeholder={t.forms.designer.detail.placeholders.default} className={inputClass} />;
  }
}

// 列编辑器
function ColumnEditor({
  column,
  onChange,
  onClose,
  t,
}: {
  column: DesignField;
  onChange: (updates: Partial<DesignField>) => void;
  onClose: () => void;
  t: ReturnType<typeof useTranslation>['t'];
}) {
  return (
    <div className="space-y-4 py-2">
      <div className="space-y-1.5">
        <Label className="text-xs text-gray-500">{t.forms.designer.detail.editor.columnTitle}</Label>
        <Input
          value={column.label}
          onChange={(e) => onChange({ label: e.target.value })}
          className="h-8 text-sm"
        />
      </div>

      <div className="space-y-1.5">
        <Label className="text-xs text-gray-500">{t.forms.designer.detail.editor.fieldKey}</Label>
        <Input
          value={column.name}
          onChange={(e) => onChange({ name: e.target.value })}
          className="h-8 text-sm font-mono"
        />
      </div>

      {(column.type === 'select' || column.type === 'multiSelect') && (
        <div className="space-y-1.5">
          <Label className="text-xs text-gray-500">{t.forms.designer.detail.editor.optionsPerLine}</Label>
          <textarea
            value={(column.options || []).map((o) => o.label).join('\n')}
            onChange={(e) => {
              const options = e.target.value
                .split('\n')
                .filter(Boolean)
                .map((label, i) => ({
                  label,
                  value: `option_${i + 1}`,
                }));
              onChange({ options });
            }}
            className="w-full h-24 px-3 py-2 border border-gray-200 rounded text-sm resize-none"
            placeholder={t.forms.designer.detail.editor.optionsPlaceholder}
          />
        </div>
      )}

      <div className="flex items-center justify-between py-1">
        <span className="text-sm text-gray-600">{t.forms.designer.detail.editor.required}</span>
        <Switch
          checked={column.required || false}
          onCheckedChange={(checked) => onChange({ required: checked })}
          className="scale-90"
        />
      </div>

      <div className="flex justify-end gap-2 pt-2">
        <Button variant="outline" size="sm" onClick={onClose}>
          {t.forms.designer.detail.editor.done}
        </Button>
      </div>
    </div>
  );
}
