/**
 * 栅格布局字段预览组件
 * 用于在表单预览模式下渲染栅格及其子字段
 */

import React from 'react';
import { Row, Col, Form, Input } from 'antd';
import type { FieldConfig, FormConfig } from '../types';
import type { FieldState } from '../utils/linkageHelper';
import { mergeValidationRules } from '../utils/validationHelper';
import { computeFieldState, FieldClassifier } from '../utils/fieldStateHelper';
import { computeGridColSpan } from '../utils/formLayoutHelper';
import FieldRenderer from './FieldRenderer';

/**
 * 隐藏字段组件（内部使用）
 * 用于渲染隐藏字段（不显示任何 UI，但参与表单提交）
 */
const HiddenField: React.FC<{ fieldName: string }> = ({ fieldName }) => {
  return (
    <Form.Item name={fieldName} noStyle>
      <Input type="hidden" />
    </Form.Item>
  );
};

interface GridFieldPreviewProps {
  field: FieldConfig;
  formConfig?: FormConfig;
  fieldStates?: Record<string, FieldState>; // ✅ 新增：支持联动规则状态
}

const GridFieldPreview: React.FC<GridFieldPreviewProps> = ({ 
  field, 
  formConfig,
  fieldStates = {} // ✅ 默认值为空对象
}) => {
  const columns = field.columns || 2;
  const children = field.children || Array(columns).fill([]);

  const renderFieldItem = (childField: FieldConfig) => {
    // ✅ 使用传入的 fieldStates 计算字段最终状态
    const fieldState = fieldStates[childField.name] || {};
    const computedState = computeFieldState(childField, fieldState);

    // 如果字段被隐藏，使用隐藏字段组件
    if (!computedState.isVisible) {
        return (
          <HiddenField
            key={childField.id}
            fieldName={childField.name}
          />
        );
    }

    // 使用统一的字段分类器判断布局组件
    const fieldType = FieldClassifier.classify(childField);
    
    // ✅ 对于嵌套的栅格，递归调用 GridFieldPreview 而不是 FieldRenderer
    // 这样可以正确传递 fieldStates，避免渲染空的容器 div
    if (fieldType === 'grid') {
      return (
        <GridFieldPreview
          key={childField.id}
          field={childField}
          formConfig={formConfig}
          fieldStates={fieldStates}
        />
      );
    }
    
    // 其他布局组件（文本、分割线）正常渲染
    if (fieldType === 'layout') {
      return (
        <div key={childField.id} style={{ marginBottom: 8 }}>
          <FieldRenderer field={childField} isPreview={true} />
        </div>
      );
    }

    // 根据表单配置决定布局方式
    const isVertical = formConfig?.labelAlign === 'top';
    
    // 合并验证规则（使用统一的工具函数）
    const allRules = mergeValidationRules(childField, computedState.isRequired);
    
    // 普通表单字段用 Form.Item 包裹
    return (
      <Form.Item
        key={childField.id}
        label={childField.label}
        name={childField.name}
        colon={true}
        labelCol={isVertical ? { span: 24 } : { span: 8 }}
        wrapperCol={isVertical ? { span: 24 } : { span: 16 }}
        rules={allRules}
      >
        <FieldRenderer
          field={{
            ...childField,
            disabled: computedState.isDisabled,
            readonly: computedState.isReadonly,
          }}
          isPreview={true}
        />
      </Form.Item>
    );
  };

  // ✅ 检查栅格内是否有可见字段
  const hasVisibleFields = children.some((columnFields) => 
    columnFields.some((childField) => {
      const fieldState = fieldStates[childField.name] || {};
      const computedState = computeFieldState(childField, fieldState);
      return computedState.isVisible;
    })
  );

  // ✅ 如果栅格内所有字段都被隐藏，不渲染容器 div
  if (!hasVisibleFields) {
    return (
      <>
        {children.flat().map((childField: FieldConfig) => (
          <HiddenField key={childField.id} fieldName={childField.name} />
        ))}
      </>
    );
  }

  return (
    <div style={{ marginBottom: 8 }}>
      <Row gutter={field.gutter || 16}>
        {children.map((columnFields, colIndex) => {
          const colSpan = computeGridColSpan(field.columnSpans, columns, colIndex);
          return (
            <Col key={colIndex} span={colSpan}>
              {columnFields.map((childField: FieldConfig) => renderFieldItem(childField))}
            </Col>
          );
        })}
      </Row>
    </div>
  );
};

export default GridFieldPreview;

