/**
 * 属性面板组件 - 钉钉/飞书风格
 * Tab 切换：表单设置 / 页面属性
 */

'use client';

import React, { useState } from 'react';
import {
  Plus,
  Trash2,
  GripVertical,
  X,
  ChevronDown,
  ChevronRight,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useDesignerStore } from './useDesignerStore';
import { FIELD_TYPES, type DesignField } from './types';
import { useTranslation } from '@/hooks/useTranslation';
import { getFieldTypeLabel } from './fieldI18n';

// 递归查找字段（包括容器和分组内的字段）
function findFieldById(fields: DesignField[], id: string): DesignField | undefined {
  for (const field of fields) {
    if (field.id === id) {
      return field;
    }
    // 检查布局容器内的字段
    if (field.type === 'container' && field.props?.columns) {
      const columns = field.props.columns as Array<{ id: string; fields: DesignField[] }>;
      for (const column of columns) {
        const found = findFieldById(column.fields || [], id);
        if (found) {
          return found;
        }
      }
    }
    // 检查分组内的字段
    if (field.type === 'group' && field.props?.fields) {
      const groupFields = field.props.fields as DesignField[];
      const found = findFieldById(groupFields, id);
      if (found) {
        return found;
      }
    }
    // 检查子表单内的字段
    if (field.type === 'detail' && field.children) {
      const found = findFieldById(field.children, id);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
}

// 查找字段所属的容器/分组/子表单信息
type FieldContainerInfo = { 
  containerId: string; 
  containerType: 'container' | 'group' | 'detail';
  columnIndex?: number;  // 仅容器使用
  fieldIndex: number;
};

function findFieldContainer(fields: DesignField[], targetId: string): FieldContainerInfo | null {
  for (const field of fields) {
    // 检查布局容器
    if (field.type === 'container' && field.props?.columns) {
      const columns = field.props.columns as Array<{ id: string; fields: DesignField[] }>;
      for (let colIndex = 0; colIndex < columns.length; colIndex++) {
        const fieldIndex = columns[colIndex].fields?.findIndex(f => f.id === targetId) ?? -1;
        if (fieldIndex !== -1) {
          return { containerId: field.id, containerType: 'container', columnIndex: colIndex, fieldIndex };
        }
      }
    }
    // 检查分组
    if (field.type === 'group' && field.props?.fields) {
      const groupFields = field.props.fields as DesignField[];
      const fieldIndex = groupFields.findIndex(f => f.id === targetId);
      if (fieldIndex !== -1) {
        return { containerId: field.id, containerType: 'group', fieldIndex };
      }
    }
    // ✅ 检查子表单（新增）
    if (field.type === 'detail' && field.children) {
      const fieldIndex = field.children.findIndex(f => f.id === targetId);
      if (fieldIndex !== -1) {
        return { containerId: field.id, containerType: 'detail', fieldIndex };
      }
    }
  }
  return null;
}

// 可折叠组
function CollapsibleSection({
  title,
  defaultOpen = true,
  children,
}: {
  title: string;
  defaultOpen?: boolean;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(defaultOpen);

  return (
    <div className="border-b border-gray-100">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1.5 w-full px-4 py-2.5 text-left hover:bg-gray-50"
      >
        {open ? (
          <ChevronDown className="w-3.5 h-3.5 text-gray-400" />
        ) : (
          <ChevronRight className="w-3.5 h-3.5 text-gray-400" />
        )}
        <span className="text-xs font-medium text-gray-700">{title}</span>
      </button>
      {open && <div className="px-4 pb-3 space-y-3">{children}</div>}
    </div>
  );
}

// 选项编辑器
function OptionsEditor({
  options,
  onChange,
  t,
}: {
  options: Array<{ label: string; value: string }>;
  onChange: (options: Array<{ label: string; value: string }>) => void;
  t: ReturnType<typeof useTranslation>['t'];
}) {
  const addOption = () => {
    const newIndex = options.length + 1;
    onChange([
      ...options,
      {
        label: t.forms.designer.defaults.optionLabel.replace('{index}', String(newIndex)),
        value: `option${newIndex}`,
      },
    ]);
  };

  const updateOption = (index: number, field: 'label' | 'value', value: string) => {
    const newOptions = [...options];
    if (field === 'label') {
      // 当更新 label 时，同时更新 value 为 label（确保 enum 值正确）
      newOptions[index] = { label: value, value: value };
    } else {
      newOptions[index] = { ...newOptions[index], [field]: value };
    }
    onChange(newOptions);
  };

  const removeOption = (index: number) => {
    onChange(options.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <Label className="text-xs text-gray-500">{t.forms.designer.propertyPanel.options.listTitle}</Label>
        <button
          onClick={addOption}
          className="flex items-center gap-0.5 text-xs text-blue-600 hover:text-blue-700"
        >
          <Plus className="w-3 h-3" /> {t.forms.designer.propertyPanel.options.add}
        </button>
      </div>
      <div className="space-y-1.5 max-h-36 overflow-y-auto">
        {options.map((option, index) => (
          <div key={index} className="flex items-center gap-1.5 group">
            <GripVertical className="w-3.5 h-3.5 text-gray-300 cursor-grab" />
            <Input
              value={option.label}
              onChange={(e) => updateOption(index, 'label', e.target.value)}
              placeholder={t.forms.designer.propertyPanel.placeholders.option}
              className="h-7 text-xs flex-1"
            />
            <button
              onClick={() => removeOption(index)}
              className="p-1 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100"
            >
              <X className="w-3 h-3" />
            </button>
          </div>
        ))}
      </div>
      {options.length === 0 && (
        <p className="text-xs text-gray-400 text-center py-2">{t.forms.designer.propertyPanel.options.emptyHint}</p>
      )}
    </div>
  );
}

// 表单属性 Tab
function FormSettingsTab() {
  const { t } = useTranslation();
  return (
    <div className="text-xs text-gray-500 text-center py-12">
      {t.forms.designer.propertyPanel.formSettings.placeholder}
      <br />
      <span className="text-gray-400">{t.forms.designer.propertyPanel.formSettings.developing}</span>
    </div>
  );
}

// 属性行组件 - 统一的行内布局
function PropertyRow({
  label,
  children,
  action,
}: {
  label: string;
  children: React.ReactNode;
  action?: React.ReactNode;
}) {
  return (
    <div className="flex items-center gap-3 px-4 py-2.5 border-b border-gray-100">
      <span className="text-xs text-gray-500 flex-shrink-0 w-14">{label}</span>
      <div className="flex-1 min-w-0">{children}</div>
      {action && <div className="flex-shrink-0">{action}</div>}
    </div>
  );
}

// 字段属性 Tab
function FieldPropertiesTab() {
  const { t } = useTranslation();
  const { fields, selectedFieldId, updateField } = useDesignerStore();
  
  // 递归查找选中的字段（包括容器内的字段）
  const selectedField = selectedFieldId ? findFieldById(fields, selectedFieldId) : undefined;
  
  // 查找字段是否在容器内
  const containerInfo = selectedFieldId ? findFieldContainer(fields, selectedFieldId) : null;
  
  // 调试日志
  console.log('📋 PropertyPanel 渲染:', {
    selectedFieldId,
    selectedField: selectedField ? { id: selectedField.id, type: selectedField.type, label: selectedField.label, name: selectedField.name } : null,
    containerInfo,
  });

  if (!selectedField) {
    return (
      <div className="text-xs text-gray-400 text-center py-12">
        {t.forms.designer.propertyPanel.emptyHint}
      </div>
    );
  }

  const handleChange = (updates: Partial<DesignField>) => {
    if (containerInfo) {
      const container = fields.find(f => f.id === containerInfo.containerId);
      if (!container) return;
      
      if (containerInfo.containerType === 'container' && container.props?.columns && containerInfo.columnIndex !== undefined) {
        // 字段在布局容器内，需要更新容器的 props.columns
        const columns = [...(container.props.columns as Array<{ id: string; fields: DesignField[] }>)];
        const columnFields = [...columns[containerInfo.columnIndex].fields];
        columnFields[containerInfo.fieldIndex] = { ...columnFields[containerInfo.fieldIndex], ...updates };
        columns[containerInfo.columnIndex] = { ...columns[containerInfo.columnIndex], fields: columnFields };
        updateField(containerInfo.containerId, { props: { ...container.props, columns } });
      } else if (containerInfo.containerType === 'group' && container.props?.fields) {
        // 字段在分组内，需要更新分组的 props.fields
        const groupFields = [...(container.props.fields as DesignField[])];
        groupFields[containerInfo.fieldIndex] = { ...groupFields[containerInfo.fieldIndex], ...updates };
        updateField(containerInfo.containerId, { props: { ...container.props, fields: groupFields } });
      } else if (containerInfo.containerType === 'detail' && container.children) {
        // ✅ 字段在子表单内，需要更新子表单的 children
        const newChildren = [...container.children];
        newChildren[containerInfo.fieldIndex] = { ...newChildren[containerInfo.fieldIndex], ...updates };
        updateField(containerInfo.containerId, { children: newChildren });
      }
    } else {
      // 顶级字段，直接更新
      updateField(selectedField.id, updates);
    }
  };

  const fieldConfig = FIELD_TYPES.find((f) => f.type === selectedField.type);
  const fieldTypeLabel = getFieldTypeLabel(
    t,
    selectedField.type,
    fieldConfig?.label || selectedField.type
  );
  const hasOptions = ['select', 'multiSelect', 'radio', 'checkbox'].includes(selectedField.type);
  const isTextField = ['text', 'textarea', 'email', 'phone', 'url'].includes(selectedField.type);
  const isNumberField = ['number', 'money'].includes(selectedField.type);
  const isCurrencyField = selectedField.type === 'currency';
  const isLayoutField = ['divider', 'description'].includes(selectedField.type);
  const isGroupField = selectedField.type === 'group';
  const isDetailColumn = containerInfo?.containerType === 'detail';

  // 状态判断 - 用于单选效果（不包含必填，必填在校验部分）
  const isNormal = !selectedField.disabled && !selectedField.props?.readonly && !selectedField.hidden;

  return (
    <div>
      {/* 字段类型标识 */}
      <div className="px-4 py-2.5 bg-gray-50 border-b border-gray-100">
        <span className="text-xs text-gray-500">
          {isDetailColumn
            ? t.forms.designer.propertyPanel.detailColumnPrefix.replace('{label}', fieldTypeLabel)
            : fieldTypeLabel}
        </span>
      </div>

      {/* 组件标识 - 放在最上方 */}
      <PropertyRow label={t.forms.designer.propertyPanel.labels.componentId}>
        <Input
          value={selectedField.name}
          onChange={(e) => handleChange({ name: e.target.value })}
          className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0 font-mono"
        />
      </PropertyRow>

      {/* 标题 */}
      {(!isLayoutField || isGroupField) && (
        <PropertyRow label={t.forms.designer.propertyPanel.labels.title}>
          <Input
            value={selectedField.label}
            onChange={(e) => handleChange({ label: e.target.value })}
            className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
          />
        </PropertyRow>
      )}

      {/* 提示文字 */}
      {!isLayoutField && !isGroupField && !['switch', 'checkbox', 'radio', 'file', 'image'].includes(selectedField.type) && (
        <PropertyRow label={t.forms.designer.propertyPanel.labels.placeholder}>
          <Input
            value={selectedField.placeholder || ''}
            onChange={(e) => handleChange({ placeholder: e.target.value })}
            placeholder={t.forms.designer.propertyPanel.placeholders.input}
            className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
          />
        </PropertyRow>
      )}

      {/* 说明 */}
      <PropertyRow label={t.forms.designer.propertyPanel.labels.description}>
        <Input
          value={selectedField.description || ''}
          onChange={(e) => handleChange({ description: e.target.value })}
          placeholder={t.forms.designer.propertyPanel.placeholders.description}
          className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
        />
      </PropertyRow>

      {/* 默认值 - 根据字段类型显示不同输入方式 */}
      {!isLayoutField && !isGroupField && selectedField.type !== 'container' && selectedField.type !== 'detail' && (
        (() => {
          const fieldType = selectedField.type;
          
          // 开关类型
          if (fieldType === 'switch') {
            return (
              <div className="flex items-center gap-3 px-4 py-2.5 border-b border-gray-100">
                <span className="text-xs text-gray-500 flex-shrink-0 w-14">{t.forms.designer.propertyPanel.labels.defaultValue}</span>
                <div className="flex-1" />
                <Switch
                  checked={selectedField.defaultValue === true}
                  onCheckedChange={(checked) => handleChange({ defaultValue: checked })}
                  className="scale-75"
                />
              </div>
            );
          }
          
          // 选择类型（单选、多选、下拉等）
          if (['select', 'radio'].includes(fieldType)) {
            const options = selectedField.options || [];
            return (
              <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultValue}>
                <Select
                  value={(selectedField.defaultValue as string) || '__none__'}
                  onValueChange={(value) => handleChange({ defaultValue: value === '__none__' ? undefined : value })}
                >
                  <SelectTrigger className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0">
                    <SelectValue placeholder={t.forms.designer.propertyPanel.placeholders.select} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__" className="text-xs text-gray-400">
                      {t.forms.designer.propertyPanel.select.noneLabel}
                    </SelectItem>
                    {options.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value} className="text-xs">
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </PropertyRow>
            );
          }
          
          // 多选类型
          if (['multiSelect', 'checkbox'].includes(fieldType)) {
            const options = selectedField.options || [];
            const currentValues = (selectedField.defaultValue as string[]) || [];
            return (
              <div className="px-4 py-2.5 border-b border-gray-100">
                <div className="text-xs text-gray-500 mb-2">{t.forms.designer.propertyPanel.labels.defaultValue}</div>
                <div className="flex flex-wrap gap-1.5">
                  {options.map((opt) => {
                    const isChecked = currentValues.includes(opt.value);
                    return (
                      <label
                        key={opt.value}
                        className={`
                          flex items-center px-2 py-0.5 rounded cursor-pointer text-xs transition-colors
                          ${isChecked 
                            ? 'bg-blue-50 text-blue-600 font-medium' 
                            : 'bg-gray-50 text-gray-500 hover:bg-gray-100'
                          }
                        `}
                      >
                        <input
                          type="checkbox"
                          checked={isChecked}
                          onChange={(e) => {
                            const newValues = e.target.checked
                              ? [...currentValues, opt.value]
                              : currentValues.filter((v) => v !== opt.value);
                            handleChange({ defaultValue: newValues.length > 0 ? newValues : undefined });
                          }}
                          className="sr-only"
                        />
                        {opt.label}
                      </label>
                    );
                  })}
                  {options.length === 0 && (
                    <span className="text-xs text-gray-400">{t.forms.designer.propertyPanel.options.emptyHint}</span>
                  )}
                </div>
              </div>
            );
          }
          
          // 日期类型
          if (fieldType === 'date') {
            return (
              <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultValue}>
                <Input
                  type="date"
                  value={(selectedField.defaultValue as string) || ''}
                  onChange={(e) => handleChange({ defaultValue: e.target.value || undefined })}
                  className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
                />
              </PropertyRow>
            );
          }
          
          // 日期时间类型
          if (fieldType === 'datetime') {
            return (
              <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultValue}>
                <Input
                  type="datetime-local"
                  value={(selectedField.defaultValue as string) || ''}
                  onChange={(e) => handleChange({ defaultValue: e.target.value || undefined })}
                  className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
                />
              </PropertyRow>
            );
          }
          
          // 数字类型
          if (['number', 'money'].includes(fieldType)) {
            return (
              <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultValue}>
                <Input
                  type="number"
                  value={typeof selectedField.defaultValue === 'number' ? selectedField.defaultValue : ''}
                  onChange={(e) => handleChange({ 
                    defaultValue: e.target.value ? parseFloat(e.target.value) : undefined 
                  })}
                  placeholder={t.forms.designer.propertyPanel.placeholders.number}
                  className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
                />
              </PropertyRow>
            );
          }
          
          // 金额类型（特殊处理）
          if (fieldType === 'currency') {
            return (
              <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultAmount}>
                <Input
                  type="number"
                  value={(selectedField.defaultValue as { amount?: number })?.amount ?? ''}
                  onChange={(e) => handleChange({ 
                    defaultValue: e.target.value 
                      ? { 
                          amount: parseFloat(e.target.value), 
                          currency: (selectedField.defaultValue as { currency?: string })?.currency || selectedField.currencyType || 'CNY'
                        } 
                      : undefined 
                  })}
                  placeholder={t.forms.designer.propertyPanel.placeholders.amount}
                  className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
                />
              </PropertyRow>
            );
          }
          
          // 文件/图片类型不支持默认值
          if (['file', 'image'].includes(fieldType)) {
            return null;
          }
          
          // 默认：文本类型（text, textarea, email, phone, url 等）
          return (
            <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultValue}>
              <Input
                value={(selectedField.defaultValue as string) || ''}
                onChange={(e) => handleChange({ defaultValue: e.target.value || undefined })}
                placeholder={t.forms.designer.propertyPanel.placeholders.defaultValue}
                className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
              />
            </PropertyRow>
          );
        })()
      )}

      {/* 状态 - 单选互斥 */}
      {!isLayoutField && (
        <div className="flex items-center gap-3 px-4 py-2.5 border-b border-gray-100">
          <span className="text-xs text-gray-500 flex-shrink-0 w-14">{t.forms.designer.propertyPanel.labels.status}</span>
          <div className="flex items-center gap-1 flex-1">
            {/* 普通 */}
            <button
              onClick={() => handleChange({ 
                disabled: false, 
                hidden: false,
                props: { ...selectedField.props, readonly: false }
              })}
              className={`
                px-2 py-0.5 text-xs rounded transition-colors
                ${isNormal
                  ? 'bg-blue-50 text-blue-600 font-medium'
                  : 'text-gray-500 hover:bg-gray-100'
                }
              `}
            >
              {t.forms.designer.propertyPanel.statusOptions.normal}
            </button>
            {/* 禁用 */}
            <button
              onClick={() => handleChange({ 
                disabled: true,
                hidden: false,
                props: { ...selectedField.props, readonly: false }
              })}
              className={`
                px-2 py-0.5 text-xs rounded transition-colors
                ${selectedField.disabled
                  ? 'bg-blue-50 text-blue-600 font-medium'
                  : 'text-gray-500 hover:bg-gray-100'
                }
              `}
            >
              {t.forms.designer.propertyPanel.statusOptions.disabled}
            </button>
            {/* 只读 */}
            <button
              onClick={() => handleChange({ 
                disabled: false,
                hidden: false,
                props: { ...selectedField.props, readonly: true }
              })}
              className={`
                px-2 py-0.5 text-xs rounded transition-colors
                ${selectedField.props?.readonly
                  ? 'bg-blue-50 text-blue-600 font-medium'
                  : 'text-gray-500 hover:bg-gray-100'
                }
              `}
            >
              {t.forms.designer.propertyPanel.statusOptions.readonly}
            </button>
            {/* 隐藏 */}
            <button
              onClick={() => handleChange({ 
                disabled: false,
                hidden: true,
                props: { ...selectedField.props, readonly: false }
              })}
              className={`
                px-2 py-0.5 text-xs rounded transition-colors
                ${selectedField.hidden
                  ? 'bg-blue-50 text-blue-600 font-medium'
                  : 'text-gray-500 hover:bg-gray-100'
                }
              `}
            >
              {t.forms.designer.propertyPanel.statusOptions.hidden}
            </button>
          </div>
        </div>
      )}

      {/* 校验 - 必填 */}
      {!isLayoutField && (
        <div className="flex items-center gap-3 px-4 py-2.5 border-b border-gray-100">
          <span className="text-xs text-gray-500 flex-shrink-0 w-14">{t.forms.designer.propertyPanel.labels.required}</span>
          <div className="flex items-center gap-1 flex-1">
            <button
              onClick={() => handleChange({ required: false })}
              className={`
                px-2 py-0.5 text-xs rounded transition-colors
                ${!selectedField.required
                  ? 'bg-blue-50 text-blue-600 font-medium'
                  : 'text-gray-500 hover:bg-gray-100'
                }
              `}
            >
              {t.forms.designer.propertyPanel.yesNo.no}
            </button>
            <button
              onClick={() => handleChange({ required: true })}
              className={`
                px-2 py-0.5 text-xs rounded transition-colors
                ${selectedField.required
                  ? 'bg-blue-50 text-blue-600 font-medium'
                  : 'text-gray-500 hover:bg-gray-100'
                }
              `}
            >
              {t.forms.designer.propertyPanel.yesNo.yes}
            </button>
          </div>
        </div>
      )}

      {/* 选项设置 */}
      {hasOptions && (
        <CollapsibleSection title={t.forms.designer.propertyPanel.labels.optionsSettings}>
          <OptionsEditor
            options={selectedField.options || []}
            onChange={(options) => handleChange({ options })}
            t={t}
          />
        </CollapsibleSection>
      )}

      {/* 文本字段 - 长度限制 */}
      {isTextField && (
        <>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.minLength}>
            <Input
              type="number"
              min={0}
              value={selectedField.validation?.minLength || ''}
              onChange={(e) => handleChange({
                validation: {
                  ...selectedField.validation,
                  minLength: e.target.value ? parseInt(e.target.value) : undefined,
                },
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.noLimit}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.maxLength}>
            <Input
              type="number"
              min={0}
              value={selectedField.validation?.maxLength || ''}
              onChange={(e) => handleChange({
                validation: {
                  ...selectedField.validation,
                  maxLength: e.target.value ? parseInt(e.target.value) : undefined,
                },
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.noLimit}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
        </>
      )}

      {/* 数字字段 - 范围限制 */}
      {(isNumberField || isCurrencyField) && (
        <>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.minValue}>
            <Input
              type="number"
              value={selectedField.validation?.min ?? ''}
              onChange={(e) => handleChange({
                validation: {
                  ...selectedField.validation,
                  min: e.target.value ? parseFloat(e.target.value) : undefined,
                },
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.noLimit}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.maxValue}>
            <Input
              type="number"
              value={selectedField.validation?.max ?? ''}
              onChange={(e) => handleChange({
                validation: {
                  ...selectedField.validation,
                  max: e.target.value ? parseFloat(e.target.value) : undefined,
                },
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.noLimit}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
        </>
      )}

      {/* 数字字段 - 小数位数和前后缀 */}
      {isNumberField && (
        <>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.precision}>
            <Input
              type="number"
              min={0}
              max={10}
              value={selectedField.precision ?? ''}
              onChange={(e) => handleChange({
                precision: e.target.value ? parseInt(e.target.value) : undefined,
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.noLimit}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.prefix}>
            <Input
              value={selectedField.prefix || ''}
              onChange={(e) => handleChange({ prefix: e.target.value })}
              placeholder={t.forms.designer.propertyPanel.placeholders.prefixExample}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.suffix}>
            <Input
              value={selectedField.suffix || ''}
              onChange={(e) => handleChange({ suffix: e.target.value })}
              placeholder={t.forms.designer.propertyPanel.placeholders.suffixExample}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
        </>
      )}

      {/* 金额字段设置 */}
      {isCurrencyField && (
        <>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.precision}>
            <Input
              type="number"
              min={0}
              max={10}
              value={selectedField.precision ?? 2}
              onChange={(e) => handleChange({
                precision: e.target.value ? parseInt(e.target.value) : 2,
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.currencyPrecision}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.defaultCurrency}>
            <Select
              value={selectedField.currencyType || 'CNY'}
              onValueChange={(value) => handleChange({ currencyType: value })}
            >
              <SelectTrigger className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="CNY" className="text-xs">🇨🇳 {t.forms.designer.propertyPanel.currency.cny}</SelectItem>
                <SelectItem value="USD" className="text-xs">🇺🇸 {t.forms.designer.propertyPanel.currency.usd}</SelectItem>
                <SelectItem value="EUR" className="text-xs">🇪🇺 {t.forms.designer.propertyPanel.currency.eur}</SelectItem>
                <SelectItem value="JPY" className="text-xs">🇯🇵 {t.forms.designer.propertyPanel.currency.jpy}</SelectItem>
                <SelectItem value="GBP" className="text-xs">🇬🇧 {t.forms.designer.propertyPanel.currency.gbp}</SelectItem>
                <SelectItem value="HKD" className="text-xs">🇭🇰 {t.forms.designer.propertyPanel.currency.hkd}</SelectItem>
              </SelectContent>
            </Select>
          </PropertyRow>
          <div className="flex items-center gap-3 px-4 py-2.5 border-b border-gray-100">
            <span className="text-xs text-gray-500 flex-shrink-0 w-14">{t.forms.designer.propertyPanel.labels.allowCurrencySelect}</span>
            <div className="flex-1" />
            <Switch
              checked={selectedField.showCurrencySelect !== false}
              onCheckedChange={(checked) => handleChange({ showCurrencySelect: checked })}
              className="scale-75"
            />
          </div>
          {selectedField.showCurrencySelect !== false && (
            <div className="px-4 py-2.5 border-b border-gray-100">
              <div className="text-xs text-gray-500 mb-2">{t.forms.designer.propertyPanel.labels.allowedCurrencies}</div>
              <div className="grid grid-cols-3 gap-1.5">
                {[
                  { value: 'CNY', label: `🇨🇳 ${t.forms.designer.propertyPanel.currency.cnyShort}` },
                  { value: 'USD', label: `🇺🇸 ${t.forms.designer.propertyPanel.currency.usdShort}` },
                  { value: 'EUR', label: `🇪🇺 ${t.forms.designer.propertyPanel.currency.eurShort}` },
                  { value: 'JPY', label: `🇯🇵 ${t.forms.designer.propertyPanel.currency.jpyShort}` },
                  { value: 'GBP', label: `🇬🇧 ${t.forms.designer.propertyPanel.currency.gbpShort}` },
                  { value: 'HKD', label: `🇭🇰 ${t.forms.designer.propertyPanel.currency.hkdShort}` },
                ].map((currency) => {
                  const allowedCurrencies = selectedField.allowedCurrencies || ['CNY', 'USD', 'EUR', 'JPY', 'GBP', 'HKD'];
                  const isChecked = allowedCurrencies.includes(currency.value);
                  return (
                    <label
                      key={currency.value}
                      className={`
                        flex items-center justify-center p-1.5 rounded cursor-pointer text-xs transition-colors
                        ${isChecked 
                          ? 'bg-blue-50 text-blue-600 font-medium' 
                          : 'bg-gray-50 text-gray-500 hover:bg-gray-100'
                        }
                      `}
                    >
                      <input
                        type="checkbox"
                        checked={isChecked}
                        onChange={(e) => {
                          const newCurrencies = e.target.checked
                            ? [...allowedCurrencies, currency.value]
                            : allowedCurrencies.filter((c) => c !== currency.value);
                          handleChange({ allowedCurrencies: newCurrencies });
                        }}
                        className="sr-only"
                      />
                      {currency.label}
                    </label>
                  );
                })}
              </div>
            </div>
          )}
        </>
      )}

      {/* 子表单设置 */}
      {selectedField.type === 'detail' && (
        <>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.minRows}>
            <Input
              type="number"
              min={0}
              value={selectedField.minRows ?? ''}
              onChange={(e) => handleChange({
                minRows: e.target.value ? parseInt(e.target.value) : undefined,
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.minRows}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <PropertyRow label={t.forms.designer.propertyPanel.labels.maxRows}>
            <Input
              type="number"
              min={1}
              value={selectedField.maxRows ?? ''}
              onChange={(e) => handleChange({
                maxRows: e.target.value ? parseInt(e.target.value) : undefined,
              })}
              placeholder={t.forms.designer.propertyPanel.placeholders.noLimit}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>
          <div className="px-4 py-2.5 border-b border-gray-100">
            <div className="text-xs text-gray-400 bg-gray-50 p-2 rounded">
              {t.forms.designer.propertyPanel.detailHint}
            </div>
          </div>
        </>
      )}

      {/* 布局容器设置 */}
      {selectedField.type === 'container' && (
        <>
          {/* 布局预设 */}
          <div className="px-4 py-2.5 border-b border-gray-100">
            <div className="text-xs text-gray-500 mb-2">{t.forms.designer.propertyPanel.labels.layout}</div>
            <div className="grid grid-cols-4 gap-1.5">
              {[
                { ratios: [1], label: t.forms.designer.propertyPanel.layoutPresets.col1 },
                { ratios: [1, 1], label: t.forms.designer.propertyPanel.layoutPresets.col2Equal },
                { ratios: [2, 1], label: t.forms.designer.propertyPanel.layoutPresets.col2LeftWide },
                { ratios: [1, 2], label: t.forms.designer.propertyPanel.layoutPresets.col2RightWide },
                { ratios: [1, 1, 1], label: t.forms.designer.propertyPanel.layoutPresets.col3Equal },
                { ratios: [2, 1, 1], label: t.forms.designer.propertyPanel.layoutPresets.col3LeftWide },
                { ratios: [1, 2, 1], label: t.forms.designer.propertyPanel.layoutPresets.col3MiddleWide },
                { ratios: [1, 1, 1, 1], label: t.forms.designer.propertyPanel.layoutPresets.col4Equal },
              ].map((preset, idx) => {
                const currentRatios = (selectedField.props?.layout as { ratios?: number[] })?.ratios || [1, 1];
                const isActive = JSON.stringify(currentRatios) === JSON.stringify(preset.ratios);
                return (
                  <button
                    key={idx}
                    onClick={() => handleChange({
                      props: {
                        ...selectedField.props,
                        layout: {
                          ...(selectedField.props?.layout as object || {}),
                          ratios: preset.ratios,
                        },
                      },
                    })}
                    className={`
                      h-7 border rounded flex items-center justify-center gap-0.5 p-1
                      transition-colors text-xs
                      ${isActive
                        ? 'border-blue-500 bg-blue-50 text-blue-600'
                        : 'border-gray-200 hover:border-gray-300 text-gray-400'
                      }
                    `}
                    title={preset.label}
                  >
                    {preset.ratios.map((r, i) => (
                      <div
                        key={i}
                        className={`h-full rounded-sm ${isActive ? 'bg-blue-500' : 'bg-gray-300'}`}
                        style={{ flex: r }}
                      />
                    ))}
                  </button>
                );
              })}
            </div>
          </div>

          {/* 列比例 */}
          <PropertyRow label={t.forms.designer.propertyPanel.labels.columnRatio}>
            <Input
              value={((selectedField.props?.layout as { ratios?: number[] })?.ratios || [1, 1]).join(':')}
              onChange={(e) => {
                const ratios = e.target.value.split(':').map(Number).filter(n => !isNaN(n) && n > 0);
                if (ratios.length > 0) {
                  handleChange({
                    props: {
                      ...selectedField.props,
                      layout: {
                        ...(selectedField.props?.layout as object || {}),
                        ratios,
                      },
                    },
                  });
                }
              }}
              placeholder={t.forms.designer.propertyPanel.placeholders.columnRatioExample}
              className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0"
            />
          </PropertyRow>

          {/* 列间距 */}
          <PropertyRow label={t.forms.designer.propertyPanel.labels.columnGap}>
            <Select
              value={String((selectedField.props?.layout as { gap?: number })?.gap || 16)}
              onValueChange={(v) => handleChange({
                props: {
                  ...selectedField.props,
                  layout: {
                    ...(selectedField.props?.layout as object || {}),
                    gap: parseInt(v),
                  },
                },
              })}
            >
              <SelectTrigger className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="0">{t.forms.designer.propertyPanel.gaps.none}</SelectItem>
                <SelectItem value="8">{t.forms.designer.propertyPanel.gaps.small}</SelectItem>
                <SelectItem value="16">{t.forms.designer.propertyPanel.gaps.medium}</SelectItem>
                <SelectItem value="24">{t.forms.designer.propertyPanel.gaps.large}</SelectItem>
              </SelectContent>
            </Select>
          </PropertyRow>

          {/* 行间距 */}
          <PropertyRow label={t.forms.designer.propertyPanel.labels.rowGap}>
            <Select
              value={String((selectedField.props?.layout as { rowGap?: number })?.rowGap || 16)}
              onValueChange={(v) => handleChange({
                props: {
                  ...selectedField.props,
                  layout: {
                    ...(selectedField.props?.layout as object || {}),
                    rowGap: parseInt(v),
                  },
                },
              })}
            >
              <SelectTrigger className="h-7 text-xs border-0 bg-transparent px-0 focus-visible:ring-0">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="0">{t.forms.designer.propertyPanel.gaps.none}</SelectItem>
                <SelectItem value="8">{t.forms.designer.propertyPanel.gaps.small}</SelectItem>
                <SelectItem value="16">{t.forms.designer.propertyPanel.gaps.medium}</SelectItem>
                <SelectItem value="24">{t.forms.designer.propertyPanel.gaps.large}</SelectItem>
              </SelectContent>
            </Select>
          </PropertyRow>

          <div className="px-4 py-2.5 border-b border-gray-100">
            <div className="text-xs text-gray-400 bg-gray-50 p-2 rounded">
              {t.forms.designer.propertyPanel.containerHint}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

export function PropertyPanel() {
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<'form' | 'field'>('field');

  return (
    <div className="w-80 bg-white border-l border-gray-200 flex flex-col h-full">
      {/* Tab 标题 */}
      <div className="border-b border-gray-200">
        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'form' | 'field')}>
          <TabsList className="w-full h-10 p-0 bg-transparent rounded-none">
            <TabsTrigger
              value="form"
              className="flex-1 h-10 rounded-none border-b-2 border-transparent 
                data-[state=active]:border-blue-500 data-[state=active]:bg-transparent
                text-xs"
            >
              {t.forms.designer.propertyPanel.tabs.formSettings}
            </TabsTrigger>
            <TabsTrigger
              value="field"
              className="flex-1 h-10 rounded-none border-b-2 border-transparent 
                data-[state=active]:border-blue-500 data-[state=active]:bg-transparent
                text-xs"
            >
              {t.forms.designer.propertyPanel.tabs.pageProperties}
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {/* Tab 内容 */}
      <div className="flex-1 overflow-y-auto">
        {activeTab === 'form' ? (
          <FormSettingsTab />
        ) : (
          <FieldPropertiesTab />
        )}
      </div>
    </div>
  );
}
