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

import React, { useContext } from 'react';
import { ComponentsContext } from '../Designer';
import {
  Form,
  Input,
  InputNumber,
  Select,
  Radio,
  Checkbox,
  DatePicker,
  TimePicker,
  Switch,
  Slider,
  Rate,
  Upload,
  Cascader,
  Divider,
  Button,
  Typography,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { FieldConfig } from '../types';
import GridField from './GridField';
import { useFieldOptions } from '../hooks/useFieldOptions';
import { useCascaderOptions, useCascaderLoadData } from '../hooks/useCascaderOptions';
import '../styles.css';

const { Text } = Typography;

const { TextArea } = Input;

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;
    console.log('✅ FieldRenderer: 使用自定义渲染组件', {
      fieldType: field.type,
      isPreview,
      hasRenderer: !!componentMeta.FieldRendererComponent
    });
    return <CustomRenderer field={field} value={value} onChange={onChange} isPreview={isPreview} />;
  }

  // 布局组件特殊处理
  if (field.type === 'divider') {
    return <Divider>{field.label}</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>
    );
  }

  if (field.type === 'grid') {
    return (
      <GridField 
        field={field} 
        isPreview={isPreview}
        selectedFieldId={selectedFieldId}
        onSelectField={onSelectField}
        onCopyField={onCopyField}
        onPasteToGrid={onPasteToGrid}
        onDeleteField={onDeleteField}
        labelAlign={labelAlign}
        hasClipboard={hasClipboard}
        duplicateFieldIds={duplicateFieldIds}
      />
    );
  }

  const renderField = () => {
    switch (field.type) {
      case 'input':
        return (
          <Input
            placeholder={field.placeholder}
            disabled={field.disabled}
            value={value}
            onChange={(e) => onChange?.(e.target.value)}
          />
        );

      case 'textarea':
        return (
          <TextArea
            rows={field.rows || 4}
            placeholder={field.placeholder}
            disabled={field.disabled}
            value={value}
            onChange={(e) => onChange?.(e.target.value)}
          />
        );

      case 'number':
        return (
          <InputNumber
            style={{ width: '100%' }}
            placeholder={field.placeholder}
            disabled={field.disabled}
            min={field.min}
            max={field.max}
            value={value}
            onChange={onChange}
          />
        );

      case 'select':
        return (
          <Select
            placeholder={field.placeholder}
            disabled={field.disabled}
            options={options}
            value={value}
            onChange={onChange}
            style={{ width: '100%' }}
          />
        );

      case 'radio':
        return (
          <Radio.Group
            options={options}
            disabled={field.disabled}
            value={value}
            onChange={(e) => onChange?.(e.target.value)}
          />
        );

      case 'checkbox':
        return (
          <Checkbox.Group
            options={options}
            disabled={field.disabled}
            value={value}
            onChange={onChange}
            style={{
              display: 'flex',
              flexDirection: field.checkboxLayout === 'vertical' ? 'column' : 'row',
              gap: field.checkboxLayout === 'vertical' ? '8px' : '16px',
            }}
          />
        );

      case 'date':
        return (
          <DatePicker
            style={{ width: '100%' }}
            placeholder={field.placeholder}
            disabled={field.disabled}
            value={value}
            onChange={onChange}
          />
        );

      case 'datetime':
        return (
          <DatePicker
            showTime
            style={{ width: '100%' }}
            placeholder={field.placeholder}
            disabled={field.disabled}
            value={value}
            onChange={onChange}
          />
        );

      case 'time':
        return (
          <TimePicker
            style={{ width: '100%' }}
            placeholder={field.placeholder}
            disabled={field.disabled}
            value={value}
            onChange={onChange}
          />
        );

      case 'switch':
        return (
          <Switch
            disabled={field.disabled}
            checked={value}
            onChange={onChange}
          />
        );

      case 'slider':
        return (
          <Slider
            min={field.min}
            max={field.max}
            disabled={field.disabled}
            value={value}
            onChange={onChange}
          />
        );

      case 'rate':
        return (
          <Rate
            disabled={field.disabled}
            value={value}
            onChange={onChange}
          />
        );

      case 'upload':
        return (
          <Upload
            maxCount={field.maxCount}
            disabled={field.disabled}
          >
            <Button icon={<UploadOutlined />}>上传文件</Button>
          </Upload>
        );

      // approver-selector 等扩展字段已通过插件机制处理，不在此硬编码

      case 'cascader':
        return (
          <Cascader
            style={{ width: '100%' }}
            placeholder={field.placeholder}
            disabled={field.disabled}
            options={cascadeOptions as any}
            value={value}
            onChange={onChange}
            loadData={loadData as any}
            changeOnSelect={field.dataSourceType === 'predefined'}
          />
        );

      default:
        return <Input placeholder={field.placeholder} />;
    }
  };

  // 预览模式下，外部已经用 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;

