import React, { useState, useEffect } from 'react';
import { XMarkIcon } from '@heroicons/react/24/outline';
import {
  AiClassification,
  AiClassificationFormData,
  AiClassificationFormErrors,
  validateClassificationForm,
  hasFormErrors,
  CLASSIFICATION_VALIDATION,
} from '../types/aiClassification';
import { LoadingSpinner } from './LoadingSpinner';
import { AiClassificationRealTimePreview } from './AiClassificationRealTimePreview';

interface AiClassificationFormDialogProps {
  /** 是否显示对话框 */
  isOpen: boolean;
  /** 对话框标题 */
  title: string;
  /** 表单数据 */
  formData: AiClassificationFormData;
  /** 表单错误 */
  formErrors: AiClassificationFormErrors;
  /** 是否正在提交 */
  submitting: boolean;
  /** 是否为编辑模式 */
  isEdit?: boolean;
  /** 现有分类列表（用于预览） */
  existingClassifications?: AiClassification[];
  /** 编辑中的分类ID */
  editingClassificationId?: string;
  /** 表单数据变化回调 */
  onFormDataChange: (data: AiClassificationFormData) => void;
  /** 提交回调 */
  onSubmit: () => void;
  /** 取消回调 */
  onCancel: () => void;
}

/**
 * AI分类表单对话框组件
 * 遵循前端开发规范的对话框设计，支持创建和编辑模式
 */
export const AiClassificationFormDialog: React.FC<AiClassificationFormDialogProps> = ({
  isOpen,
  title,
  formData,
  formErrors,
  submitting,
  isEdit = false,
  existingClassifications = [],
  editingClassificationId,
  onFormDataChange,
  onSubmit,
  onCancel,
}) => {
  const [localFormData, setLocalFormData] = useState<AiClassificationFormData>(formData);
  const [localErrors, setLocalErrors] = useState<AiClassificationFormErrors>({});

  // 同步外部表单数据
  useEffect(() => {
    setLocalFormData(formData);
  }, [formData]);

  // 同步外部错误
  useEffect(() => {
    setLocalErrors(formErrors);
  }, [formErrors]);

  // 处理输入变化
  const handleInputChange = (field: keyof AiClassificationFormData, value: string | number) => {
    const newData = { ...localFormData, [field]: value };
    setLocalFormData(newData);
    onFormDataChange(newData);

    // 清除对应字段的错误
    if (localErrors[field]) {
      const newErrors = { ...localErrors };
      delete newErrors[field];
      setLocalErrors(newErrors);
    }
  };

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // 验证表单
    const errors = validateClassificationForm(localFormData);
    setLocalErrors(errors);
    
    if (!hasFormErrors(errors)) {
      onSubmit();
    }
  };

  // 处理取消
  const handleCancel = () => {
    setLocalErrors({});
    onCancel();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto animate-fade-in">
      <div className="flex items-center justify-center min-h-screen pt-4 px-4 pb-20">
        {/* 美观的背景遮罩 */}
        <div
          className="fixed inset-0 bg-black bg-opacity-60 backdrop-blur-sm transition-all duration-300"
          onClick={handleCancel}
        />

        {/* 优化的对话框 */}
        <div className="relative bg-white rounded-2xl text-left overflow-hidden shadow-2xl transform transition-all duration-300 animate-scale-in max-w-3xl w-full mx-4">
          {/* 美观的标题栏 */}
          <div className="bg-gradient-to-r from-purple-50 via-pink-50 to-purple-50 px-6 py-5 border-b border-purple-200">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center shadow-sm">
                  <span className="text-white text-lg">🤖</span>
                </div>
                <h3 className="text-xl font-bold text-gray-900">
                  {title}
                </h3>
              </div>
              <button
                onClick={handleCancel}
                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-white hover:shadow-sm rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-purple-500/20"
              >
                <XMarkIcon className="h-5 w-5" />
              </button>
            </div>
          </div>

          {/* 表单内容 - 优化间距和布局 */}
          <form onSubmit={handleSubmit}>
            <div className="bg-white px-6 pb-6">
              <div className="space-y-5">
                {/* 通用错误信息 - 优化样式 */}
                {localErrors.general && (
                  <div className="rounded-xl bg-red-50 border border-red-100 p-4">
                    <div className="text-sm text-red-700 font-medium">
                      {localErrors.general}
                    </div>
                  </div>
                )}

                {/* 分类名称 - 优化字段样式 */}
                <div className="space-y-2">
                  <label htmlFor="name" className="block text-sm font-medium text-gray-700">
                    分类名称 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    id="name"
                    value={localFormData.name}
                    onChange={(e) => handleInputChange('name', e.target.value)}
                    className={`block w-full px-3 py-2 border rounded-lg shadow-sm text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 ${
                      localErrors.name
                        ? 'border-red-300 bg-red-50/50'
                        : 'border-gray-200 bg-white hover:border-gray-300'
                    }`}
                    placeholder="请输入分类名称"
                    maxLength={CLASSIFICATION_VALIDATION.NAME_MAX_LENGTH}
                    disabled={submitting}
                  />
                  {localErrors.name && (
                    <p className="text-xs text-red-600 font-medium">{localErrors.name}</p>
                  )}
                  <p className="text-xs text-gray-500">
                    {localFormData.name.length}/{CLASSIFICATION_VALIDATION.NAME_MAX_LENGTH}
                  </p>
                </div>

                {/* 提示词 - 优化文本域样式 */}
                <div className="space-y-2">
                  <label htmlFor="prompt_text" className="block text-sm font-medium text-gray-700">
                    提示词 <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    id="prompt_text"
                    rows={4}
                    value={localFormData.prompt_text}
                    onChange={(e) => handleInputChange('prompt_text', e.target.value)}
                    className={`block w-full px-3 py-2 border rounded-lg shadow-sm text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 resize-none ${
                      localErrors.prompt_text
                        ? 'border-red-300 bg-red-50/50'
                        : 'border-gray-200 bg-white hover:border-gray-300'
                    }`}
                    placeholder="请输入AI分类的提示词，描述什么样的视频属于这个分类"
                    maxLength={CLASSIFICATION_VALIDATION.PROMPT_TEXT_MAX_LENGTH}
                    disabled={submitting}
                  />
                  {localErrors.prompt_text && (
                    <p className="text-xs text-red-600 font-medium">{localErrors.prompt_text}</p>
                  )}
                  <p className="text-xs text-gray-500">
                    {localFormData.prompt_text.length}/{CLASSIFICATION_VALIDATION.PROMPT_TEXT_MAX_LENGTH}
                  </p>
                </div>

                {/* 描述 - 优化样式 */}
                <div className="space-y-2">
                  <label htmlFor="description" className="block text-sm font-medium text-gray-700">
                    描述
                  </label>
                  <textarea
                    id="description"
                    rows={2}
                    value={localFormData.description}
                    onChange={(e) => handleInputChange('description', e.target.value)}
                    className={`block w-full px-3 py-2 border rounded-lg shadow-sm text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 resize-none ${
                      localErrors.description
                        ? 'border-red-300 bg-red-50/50'
                        : 'border-gray-200 bg-white hover:border-gray-300'
                    }`}
                    placeholder="可选：添加分类的详细描述"
                    maxLength={CLASSIFICATION_VALIDATION.DESCRIPTION_MAX_LENGTH}
                    disabled={submitting}
                  />
                  {localErrors.description && (
                    <p className="text-xs text-red-600 font-medium">{localErrors.description}</p>
                  )}
                  <p className="text-xs text-gray-500">
                    {localFormData.description.length}/{CLASSIFICATION_VALIDATION.DESCRIPTION_MAX_LENGTH}
                  </p>
                </div>

                {/* 排序顺序 - 优化数字输入样式 */}
                <div className="space-y-2">
                  <label htmlFor="sort_order" className="block text-sm font-medium text-gray-700">
                    排序顺序
                  </label>
                  <input
                    type="number"
                    id="sort_order"
                    value={localFormData.sort_order}
                    onChange={(e) => handleInputChange('sort_order', parseInt(e.target.value) || 0)}
                    className={`block w-full px-3 py-2 border rounded-lg shadow-sm text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 ${
                      localErrors.sort_order
                        ? 'border-red-300 bg-red-50/50'
                        : 'border-gray-200 bg-white hover:border-gray-300'
                    }`}
                    min={CLASSIFICATION_VALIDATION.MIN_SORT_ORDER}
                    max={CLASSIFICATION_VALIDATION.MAX_SORT_ORDER}
                    disabled={submitting}
                  />
                  {localErrors.sort_order && (
                    <p className="text-xs text-red-600 font-medium">{localErrors.sort_order}</p>
                  )}
                  <p className="text-xs text-gray-500">
                    数值越小排序越靠前 ({CLASSIFICATION_VALIDATION.MIN_SORT_ORDER}-{CLASSIFICATION_VALIDATION.MAX_SORT_ORDER})
                  </p>
                </div>

                {/* 实时预览 */}
                <div>
                  <AiClassificationRealTimePreview
                    currentFormData={localFormData}
                    existingClassifications={existingClassifications}
                    isEdit={isEdit}
                    editingClassificationId={editingClassificationId}
                  />
                </div>
              </div>
            </div>

            {/* 按钮栏 */}
            <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
              <button
                type="submit"
                disabled={submitting}
                className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {submitting ? (
                  <>
                    <LoadingSpinner size="small" className="mr-2" />
                    {isEdit ? '更新中...' : '创建中...'}
                  </>
                ) : (
                  isEdit ? '更新' : '创建'
                )}
              </button>
              <button
                type="button"
                onClick={handleCancel}
                disabled={submitting}
                className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                取消
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};
