/**
 * 字段渲染器
 * 根据字段类型渲染对应的表单组件
 */

import React, { useContext } from 'react';
import { ComponentsContext } from '../Designer';
import {
  Form,
  Input,
  Divider,
  Typography,
} from 'antd';
import type { FieldConfig } from '../types';
import GridField from './GridField';
import { useFieldOptions } from '../hooks/useFieldOptions';
import { useCascaderOptions, useCascaderLoadData } from '../hooks/useCascaderOptions';
import { fieldRenderStrategyRegistry } from '../renderers/FieldRenderStrategyRegistry';
import type { FieldRenderContext } from '../renderers/IFieldRenderStrategy';
import '../styles.css';

const { Text } = Typography;

interface FieldRendererProps {
  field: FieldConfig;
  value?: any;
  onChange?: (value: any) => void;
  isPreview?: boolean; // 是否为预览模式
  selectedFieldId?: string; // 当前选中的字段ID
  onSelectField?: (fieldId: string) => void;
  onCopyField?: (fieldId: string) => void;
  onPasteToGrid?: (gridId: string, colIndex: number) => void;
  onDeleteField?: (fieldId: string) => void;
  labelAlign?: 'left' | 'right' | 'top'; // 标签对齐方式
  hasClipboard?: boolean;
  duplicateFieldIds?: Set<string>; // 冲突的字段ID集合
}

const FieldRenderer: React.FC<FieldRendererProps> = ({ 
  field, 
  value, 
  onChange, 
  isPreview = false,
  selectedFieldId,
  onSelectField,
  onCopyField,
  onPasteToGrid,
  onDeleteField,
  labelAlign = 'right',
  hasClipboard = false,
  duplicateFieldIds = new Set(),
}) => {
  // 获取字段选项和级联选项（支持静态和动态数据源）
  const options = useFieldOptions(field);
  const cascadeOptions = useCascaderOptions(field);
  const loadData = useCascaderLoadData(field);

  // 🔌 优先检查自定义渲染组件（插件式扩展）
  const allComponents = useContext(ComponentsContext);
  const componentMeta = allComponents.find(c => c.type === field.type);
  
  if (componentMeta?.FieldRendererComponent) {
    const CustomRenderer = componentMeta.FieldRendererComponent;
    return <CustomRenderer field={field} value={value} onChange={onChange} isPreview={isPreview} />;
  }

  // 布局组件特殊处理（这些组件不通过策略模式）
  if (field.type === 'divider') {
    const showText = field.showText !== false;
    const dividerText = field.dividerText || field.label || '分割线';
    const dividerColor = field.dividerColor || 'rgba(5, 5, 5, 0.06)';
    return (
      <Divider style={{ borderColor: dividerColor, color: dividerColor }}>
        {showText ? dividerText : null}
      </Divider>
    );
  }

  if (field.type === 'text') {
    return (
      <div style={{ padding: '8px 0', textAlign: field.textAlign || 'left' }}>
        <Text style={{
          fontSize: field.fontSize ? `${field.fontSize}px` : '14px',
          color: field.textColor || '#000000',
        }}>
          {field.content || '这是一段文字'}
        </Text>
      </div>
    );
  }

  // ✅ 栅格布局：只在设计模式下渲染，运行时模式由 GridFieldPreview 处理
  if (field.type === 'grid') {
    // 预览/运行时模式：不在 FieldRenderer 层处理栅格
    // 因为 FormFieldsRenderer 已经使用 GridFieldPreview 处理了
    // 避免重复渲染和丢失 fieldStates
    if (isPreview) {
      console.warn('⚠️ FieldRenderer 在预览模式下不应处理 grid 类型，应由 GridFieldPreview 处理');
      return null;
    }
    
    // 设计模式：使用 GridField（支持拖拽、选中等设计器功能）
    return (
      <GridField 
        field={field} 
        isPreview={false}
        selectedFieldId={selectedFieldId}
        onSelectField={onSelectField}
        onCopyField={onCopyField}
        onPasteToGrid={onPasteToGrid}
        onDeleteField={onDeleteField}
        labelAlign={labelAlign}
        hasClipboard={hasClipboard}
        duplicateFieldIds={duplicateFieldIds}
      />
    );
  }

  // 使用策略模式渲染字段（工厂模式获取策略）
  const strategy = fieldRenderStrategyRegistry.get(field.type);
  
  // 计算只读样式
  const isReadonly = field.readonly || false;
  const readonlyStyle = isReadonly ? {
    backgroundColor: '#f5f5f5',
    cursor: 'not-allowed',
    color: '#00000040',
  } : undefined;

  // 构造渲染上下文
  const renderContext: FieldRenderContext = {
    field,
    value,
    onChange,
    isDisabled: field.disabled || false,
    isReadonly,
    readonlyStyle,
    options,
    cascadeOptions,
    loadData,
  };

  // 渲染字段组件
  const renderField = () => {
    if (strategy) {
      return strategy.render(renderContext);
    }
    
    // 兜底策略：未注册的字段类型使用默认 Input
        return (
          <Input
            placeholder={field.placeholder}
        readOnly={isReadonly}
        disabled={field.disabled && !isReadonly}
          />
        );
  };

  // 预览模式下，外部已经用 Form.Item 包裹了，这里直接返回控件
  if (isPreview) {
    return renderField();
  }

  // 设计模式下，用 Form 和 Form.Item 包裹以显示标签，并支持动态布局
  const isVertical = labelAlign === 'top';
  
  return (
    <Form
      layout={isVertical ? 'vertical' : 'horizontal'}
      labelAlign={isVertical ? undefined : labelAlign}
    >
      <Form.Item
        label={field.label}
        required={field.required}
        style={{ marginBottom: 0 }}
        labelCol={isVertical ? undefined : { span: 6 }}
        wrapperCol={isVertical ? undefined : { span: 18 }}
      >
        {renderField()}
      </Form.Item>
    </Form>
  );
};

export default FieldRenderer;

