/**
 * FormRenderer - 表单引擎核心渲染组件
 * 
 * 基于 JSON Schema 动态渲染表单，支持：
 * - 多种字段类型（文本、数字、日期、选择器、子表单等）
 * - 自定义 UI Schema 配置
 * - 表单验证（必填、格式、范围等）
 * - 多部门提交人选择
 * - 草稿保存和正式提交
 * - 国际化支持
 * 
 * @example
 * ```tsx
 * <FormRenderer
 *   schema={jsonSchema}
 *   uiSchema={uiConfig}
 *   onSubmit={(data) => handleSubmit(data)}
 *   submitter={currentUser}
 * />
 * ```
 * 
 * @module forms
 * @see FormFieldRenderer - 字段级别渲染器
 * @see backend/src/form-engine - 后端表单引擎
 */

'use client';

import type React from 'react';
import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { AlertCircle, Save, Send } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { FormFieldRenderer } from './FormFieldRenderer';

// ============================================
// 类型定义
// ============================================

/**
 * JSON Schema 定义（标准 JSON Schema 规范）
 * @see https://json-schema.org/
 */
export interface JSONSchema {
  /** 字段类型：string | number | integer | boolean | object | array */
  type: string;
  /** 字段标题（用于显示） */
  title?: string;
  /** 字段描述 */
  description?: string;
  /** 对象类型的属性定义 */
  properties?: Record<string, JSONSchema>;
  /** 数组类型的元素定义 */
  items?: JSONSchema;
  /** 必填字段列表 */
  required?: string[];
  /** 枚举值（用于下拉选择） */
  enum?: unknown[];
  /** 枚举值对应的显示名称 */
  enumNames?: string[];
  /** 默认值 */
  default?: unknown;
  /** 格式约束（email | date | time | date-time 等） */
  format?: string;
  /** 数字最小值 */
  minimum?: number;
  /** 数字最大值 */
  maximum?: number;
  /** 字符串最小长度 */
  minLength?: number;
  /** 字符串最大长度 */
  maxLength?: number;
  /** 正则表达式验证 */
  pattern?: string;
  /** 数组最小项数 */
  minItems?: number;
  /** 数组最大项数 */
  maxItems?: number;
  /** 扩展字段：自定义类型（group | container 等） */
  'x-type'?: string;
  /** 扩展字段：布局配置 */
  'x-layout'?: { ratios: number[]; gap?: number };
  /** 扩展字段：列索引（用于布局容器） */
  'x-column'?: number;
  /** 扩展字段：列顺序（用于子表单） */
  'x-column-order'?: string[];
  /** 扩展字段：分组图标 */
  'x-icon'?: string;
  /** 扩展字段：占位符 */
  'x-placeholder'?: string;
  /** 其他扩展字段 */
  [key: string]: unknown;
}

/**
 * UI Schema 定义（控制字段渲染方式）
 */
export interface UISchema {
  /** Widget 类型（textarea | password | email | date | switch 等） */
  'ui:widget'?: string;
  /** Widget 选项配置 */
  'ui:options'?: Record<string, unknown>;
  /** 占位符文本 */
  'ui:placeholder'?: string;
  /** 帮助文本 */
  'ui:help'?: string;
  /** 是否禁用 */
  'ui:disabled'?: boolean;
  /** 是否只读 */
  'ui:readonly'?: boolean;
  /** 字段显示顺序 */
  'ui:order'?: string[];
  /** 其他 UI 配置 */
  [key: string]: unknown;
}

/**
 * 表单验证错误
 */
export interface ValidationError {
  /** 字段名称 */
  field: string;
  /** 错误消息 */
  message: string;
}

/**
 * 部门信息
 */
export interface Department {
  /** 部门 ID */
  id: string;
  /** 部门名称 */
  name: string;
}

/**
 * 提交人信息
 */
export interface SubmitterInfo {
  /** 用户 ID */
  id: string;
  /** 用户姓名 */
  name: string;
  /** 头像 URL */
  avatar?: string;
  /** 所属部门列表 */
  departments: Department[];
}

/**
 * FormRenderer 组件属性
 */
export interface FormRendererProps {
  /** JSON Schema 定义 */
  schema: JSONSchema;
  /** UI Schema 配置 */
  uiSchema?: Record<string, UISchema>;
  /** 表单数据 */
  formData?: Record<string, unknown>;
  /** 数据变化回调 */
  onChange?: (data: Record<string, unknown>) => void;
  /** 提交回调（返回表单数据和选中的部门 ID） */
  onSubmit?: (data: Record<string, unknown>, submitterDepartmentId?: string) => void | Promise<void>;
  /** 保存草稿回调 */
  onSave?: (data: Record<string, unknown>) => void | Promise<void>;
  /** 是否禁用表单 */
  disabled?: boolean;
  /** 是否显示保存按钮 */
  showSaveButton?: boolean;
  /** 是否显示提交按钮 */
  showSubmitButton?: boolean;
  /** 提交按钮文本 */
  submitButtonText?: string;
  /** 保存按钮文本 */
  saveButtonText?: string;
  /** 语言设置 */
  locale?: string;
  /** 提交者信息（如果提供则显示用户信息选择区域） */
  submitter?: SubmitterInfo;
  /** 是否显示提交者信息（默认 true，当提供 submitter 时） */
  showSubmitterInfo?: boolean;
}

// ============================================
// FormRenderer 组件
// ============================================

/**
 * 表单渲染器主组件
 * 
 * 负责：
 * - 管理表单状态
 * - 处理表单验证
 * - 渲染表单字段
 * - 处理提交和保存
 */
export function FormRenderer({
  schema,
  uiSchema = {},
  formData: initialFormData = {},
  onChange,
  onSubmit,
  onSave,
  disabled = false,
  showSaveButton = true,
  showSubmitButton = true,
  submitButtonText,
  saveButtonText,
  locale = 'zh-CN',
  submitter,
  showSubmitterInfo = true,
}: FormRendererProps) {
  // 国际化默认值：未传 button text 时按当前 locale fall back，避免硬编码中文。
  const { t } = useTranslation();
  const resolvedSubmitText = submitButtonText ?? t.forms.instance.actions.submit;
  const resolvedSaveText = saveButtonText ?? t.forms.instance.actions.saveDraft;
  // ============================================
  // 状态管理
  // ============================================

  const [formData, setFormData] = useState<Record<string, unknown>>({});
  const [errors, setErrors] = useState<ValidationError[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [saving, setSaving] = useState(false);
  const [selectedDepartmentId, setSelectedDepartmentId] = useState<string>('');
  
  // ⭐ 移除内部的防重复逻辑，完全依赖外部的 disabled prop
  // 内部只管理 UI 状态，防重复逻辑由父组件通过 disabled 控制

  // ============================================
  // 默认值提取
  // ============================================

  /**
   * 从 JSON Schema 中提取默认值
   */
  const getDefaultValues = useCallback((schemaObj: JSONSchema): Record<string, unknown> => {
    const defaults: Record<string, unknown> = {};
    const { properties = {} } = schemaObj;
    
    Object.keys(properties).forEach((fieldName) => {
      const fieldSchema = properties[fieldName];
      if (fieldSchema.default !== undefined) {
        defaults[fieldName] = fieldSchema.default;
      }
    });
    
    return defaults;
  }, []);

  /**
   * 合并默认值和初始数据（初始数据优先）
   */
  const mergedInitialData = useMemo(() => {
    const defaults = getDefaultValues(schema);
    return { ...defaults, ...initialFormData };
  }, [schema, initialFormData, getDefaultValues]);

  // ============================================
  // 副作用处理
  // ============================================

  // 初始化表单数据
  useEffect(() => {
    setFormData(mergedInitialData);
  }, [mergedInitialData]);

  // 初始化默认部门
  useEffect(() => {
    if (submitter?.departments?.length) {
      setSelectedDepartmentId(submitter.departments[0].id);
    }
  }, [submitter]);

  // ============================================
  // 表单验证
  // ============================================

  /**
   * 验证表单数据
   * @param data - 要验证的数据
   * @param validateRequired - 是否验证必填项（草稿保存时为 false）
   * @returns 验证错误列表
   */
  const validate = useCallback(
    (data: Record<string, unknown>, validateRequired = true): ValidationError[] => {
      const validationErrors: ValidationError[] = [];
      const { properties = {}, required = [] } = schema;

      // 验证必填字段
      if (validateRequired) {
        required.forEach((fieldName) => {
          const fieldValue = data[fieldName];
          const isEmpty = 
            fieldValue === undefined || 
            fieldValue === null || 
            (typeof fieldValue === 'string' && fieldValue.trim() === '');

          if (isEmpty) {
            const fieldSchema = properties[fieldName];
            const fieldTitle = fieldSchema?.title || fieldName;
            validationErrors.push({
              field: fieldName,
              message: `${fieldTitle} 是必填项`,
            });
          }
        });
      }

      // 验证字段格式和约束
      Object.keys(properties).forEach((fieldName) => {
        const fieldSchema = properties[fieldName];
        const fieldValue = data[fieldName];
        const fieldTitle = fieldSchema.title || fieldName;

        // ⭐ 验证子表单（array类型）内部的必填字段
        if (validateRequired && fieldSchema.type === 'array' && Array.isArray(fieldValue)) {
          const itemSchema = fieldSchema.items as JSONSchema | undefined;
          if (itemSchema?.type === 'object' && itemSchema.properties && itemSchema.required) {
            const itemRequired = itemSchema.required as string[];
            
            fieldValue.forEach((row: any, rowIndex: number) => {
              itemRequired.forEach((itemFieldName) => {
                const itemFieldValue = row?.[itemFieldName];
                const itemFieldSchema = (itemSchema.properties as Record<string, JSONSchema>)[itemFieldName];
                const itemFieldTitle = itemFieldSchema?.title || itemFieldName;
                
                const isEmpty = 
                  itemFieldValue === undefined || 
                  itemFieldValue === null || 
                  (typeof itemFieldValue === 'string' && itemFieldValue.trim() === '') ||
                  (typeof itemFieldValue === 'number' && isNaN(itemFieldValue));

                if (isEmpty) {
                  validationErrors.push({
                    field: `${fieldName}[${rowIndex}].${itemFieldName}`,
                    message: `${fieldTitle} 第 ${rowIndex + 1} 行的 ${itemFieldTitle} 是必填项`,
                  });
                }
              });
            });
          }
        }

        // 跳过空值
        if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
          return;
        }

        // 字符串类型验证
        if (fieldSchema.type === 'string' && typeof fieldValue === 'string') {
          // 最小长度
          if (fieldSchema.minLength && fieldValue.length < fieldSchema.minLength) {
            validationErrors.push({
              field: fieldName,
              message: `${fieldTitle} 最少需要 ${fieldSchema.minLength} 个字符`,
            });
          }

          // 最大长度
          if (fieldSchema.maxLength && fieldValue.length > fieldSchema.maxLength) {
            validationErrors.push({
              field: fieldName,
              message: `${fieldTitle} 最多 ${fieldSchema.maxLength} 个字符`,
            });
          }

          // 正则表达式验证
          if (fieldSchema.pattern) {
            const regex = new RegExp(fieldSchema.pattern);
            if (!regex.test(fieldValue)) {
              validationErrors.push({
                field: fieldName,
                message: `${fieldTitle} 格式不正确`,
              });
            }
          }

          // 邮箱格式验证
          if (fieldSchema.format === 'email') {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(fieldValue)) {
              validationErrors.push({
                field: fieldName,
                message: `${fieldTitle} 邮箱格式不正确`,
              });
            }
          }
        }

        // 数字类型验证
        if (fieldSchema.type === 'number' || fieldSchema.type === 'integer') {
          const numValue = Number(fieldValue);
          
          // 最小值
          if (fieldSchema.minimum !== undefined && numValue < fieldSchema.minimum) {
            validationErrors.push({
              field: fieldName,
              message: `${fieldTitle} 不能小于 ${fieldSchema.minimum}`,
            });
          }

          // 最大值
          if (fieldSchema.maximum !== undefined && numValue > fieldSchema.maximum) {
            validationErrors.push({
              field: fieldName,
              message: `${fieldTitle} 不能大于 ${fieldSchema.maximum}`,
            });
          }
        }
      });

      return validationErrors;
    },
    [schema]
  );

  // ============================================
  // 事件处理
  // ============================================

  /**
   * 处理字段值变化
   */
  const handleFieldChange = useCallback(
    (fieldName: string, value: unknown) => {
      const newFormData = { ...formData, [fieldName]: value };
      setFormData(newFormData);

      // 清除该字段的错误信息
      setErrors((prevErrors) => prevErrors.filter((err) => err.field !== fieldName));

      // 通知外部组件
      onChange?.(newFormData);
    },
    [formData, onChange]
  );

  /**
   * 处理保存草稿
   */
  const handleSave = async () => {
    if (!onSave || disabled || saving || submitting) return;

    setSaving(true);

    // 草稿不验证必填项（只验证格式，不验证必填）
    const validationErrors = validate(formData, false);
    setErrors(validationErrors);

    try {
      await onSave(formData);
    } catch (error) {
      console.error('Save error:', error);
    } finally {
      setSaving(false);
    }
  };

  /**
   * 处理表单提交
   */
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!onSubmit || disabled || submitting || saving) return;

    setSubmitting(true);

    // 验证所有字段（包括必填项）
    const validationErrors = validate(formData, true);
    
    // 如果有多个部门且未选择部门，添加错误
    if (submitter && submitter.departments.length > 1 && !selectedDepartmentId) {
      validationErrors.push({
        field: '_department',
        message: t.forms.instance.pleaseSelectDepartment,
      });
    }
    
    setErrors(validationErrors);

    // 如果有验证错误，停止提交并重置状态
    if (validationErrors.length > 0) {
      setSubmitting(false);
      return;
    }

    try {
      await onSubmit(formData, selectedDepartmentId || undefined);
    } catch (error) {
      console.error('Submit error:', error);
    } finally {
      setSubmitting(false);
    }
  };

  // ============================================
  // 渲染函数
  // ============================================

  /**
   * 渲染表单字段列表
   */
  const renderFields = () => {
    const { properties = {} } = schema;
    const order = uiSchema['ui:order'];
    const fieldOrder = (Array.isArray(order) ? order : Object.keys(properties)) as string[];

    return fieldOrder.map((fieldName: string) => {
      const fieldSchema = properties[fieldName];
      if (!fieldSchema) return null;

      const fieldUISchema = uiSchema[fieldName] || {};
      const fieldValue = formData[fieldName];
      const fieldErrors = errors.filter((err) => err.field === fieldName);
      const isRequired = schema.required?.includes(fieldName);

      return (
        <FormFieldRenderer
          key={fieldName}
          name={fieldName}
          schema={fieldSchema}
          uiSchema={fieldUISchema}
          value={fieldValue}
          onChange={handleFieldChange}
          disabled={disabled}
          required={isRequired}
          errors={fieldErrors}
          locale={locale}
        />
      );
    });
  };

  /**
   * 渲染提交者信息区域
   */
  const renderSubmitterInfo = () => {
    if (!submitter || !showSubmitterInfo) {
      return null;
    }
    
    const hasMultipleDepartments = submitter.departments.length > 1;
    const currentDepartment = submitter.departments.find(d => d.id === selectedDepartmentId) 
      || submitter.departments[0];
    
    return (
      <div className="grid grid-cols-2 gap-4">
        {/* 提交人 */}
        <div>
          <span className="text-sm text-gray-500">提交人</span>
          <div className="text-sm text-gray-900 mt-1">{submitter.name}</div>
        </div>
        
        {/* 提交部门 */}
        <div>
          <span className="text-sm text-gray-500">
            提交部门
            {hasMultipleDepartments && <span className="text-red-500 ml-0.5">*</span>}
          </span>
          {hasMultipleDepartments ? (
            <Select 
              value={selectedDepartmentId} 
              onValueChange={setSelectedDepartmentId}
            >
              <SelectTrigger className="mt-1">
                <SelectValue placeholder="请选择部门" />
              </SelectTrigger>
              <SelectContent>
                {submitter.departments.map((dept) => (
                  <SelectItem key={dept.id} value={dept.id}>
                    {dept.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <div className="text-sm text-gray-900 mt-1">
              {currentDepartment?.name || '-'}
            </div>
          )}
        </div>
      </div>
    );
  };

  // ============================================
  // 主渲染
  // ============================================

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* 表单标题 */}
      {schema.title && (
        <div className="p-4 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">
            {schema.title}
          </h2>
        </div>
      )}

      {/* 提交者信息 */}
      {renderSubmitterInfo()}

      {/* 全局错误提示 */}
      {errors.length > 0 && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            <div className="font-medium mb-1">请修正以下错误：</div>
            <ul className="list-disc list-inside space-y-1">
              {errors.map((error, index) => (
                <li key={index} className="text-sm">
                  {error.message}
                </li>
              ))}
            </ul>
          </AlertDescription>
        </Alert>
      )}

      {/* 表单字段 */}
      <div className="space-y-4">
        {renderFields()}
      </div>

      {/* 操作按钮 */}
      {(showSaveButton || showSubmitButton) && (
        <div className="flex gap-3 pt-4 border-t border-gray-200">
          {showSaveButton && onSave && (
            <Button
              type="button"
              variant="outline"
              onClick={handleSave}
              disabled={disabled || saving || submitting}
            >
              <Save className="w-4 h-4 mr-2" />
              {saving ? t.forms.instance.saving : resolvedSaveText}
            </Button>
          )}
          {showSubmitButton && onSubmit && (
            <Button
              type="submit"
              disabled={disabled || saving || submitting}
            >
              <Send className="w-4 h-4 mr-2" />
              {submitting ? t.forms.instance.submitting : resolvedSubmitText}
            </Button>
          )}
        </div>
      )}
    </form>
  );
}

