import React, { useState } from 'react';
import {
  XMarkIcon,
  CloudArrowUpIcon,
  DocumentIcon
} from '@heroicons/react/24/outline';
import { 
  MaterialAsset, 
  MaterialCategory,
  MATERIAL_CATEGORY_CONFIG 
} from '../../types/videoGeneration';

interface CreateMaterialAssetModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAssetCreated: (asset: MaterialAsset) => void;
}

/**
 * 创建素材模态框组件
 * 支持上传文件和填写素材信息
 */
export const CreateMaterialAssetModal: React.FC<CreateMaterialAssetModalProps> = ({
  isOpen,
  onClose,
  onAssetCreated
}) => {
  const [formData, setFormData] = useState({
    name: '',
    category: MaterialCategory.Model,
    description: '',
    tags: '',
    file: null as File | null
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [dragActive, setDragActive] = useState(false);

  if (!isOpen) return null;

  // 处理文件拖拽
  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  // 处理文件放置
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      const file = e.dataTransfer.files[0];
      handleFileSelect(file);
    }
  };

  // 处理文件选择
  const handleFileSelect = (file: File) => {
    setFormData(prev => ({ ...prev, file }));
    
    // 如果名称为空，使用文件名（去掉扩展名）
    if (!formData.name) {
      const nameWithoutExt = file.name.replace(/\.[^/.]+$/, "");
      setFormData(prev => ({ ...prev, name: nameWithoutExt }));
    }
  };

  // 处理文件输入变化
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileSelect(e.target.files[0]);
    }
  };

  // 获取文件类型
  const getFileType = (file: File): 'image' | 'video' | 'audio' | 'text' => {
    const type = file.type;
    if (type.startsWith('image/')) return 'image';
    if (type.startsWith('video/')) return 'video';
    if (type.startsWith('audio/')) return 'audio';
    return 'text';
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name.trim()) {
      alert('请输入素材名称');
      return;
    }

    setIsSubmitting(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 创建新素材对象
      const newAsset: MaterialAsset = {
        id: Date.now().toString(),
        name: formData.name.trim(),
        category: formData.category,
        type: formData.file ? getFileType(formData.file) : 'text',
        file_path: formData.file ? `/assets/${formData.category}/${formData.file.name}` : undefined,
        thumbnail_path: formData.file ? `/assets/thumbnails/${formData.file.name}_thumb.jpg` : undefined,
        description: formData.description.trim() || undefined,
        tags: formData.tags.split(',').map(tag => tag.trim()).filter(tag => tag),
        metadata: formData.file ? {
          size: formData.file.size,
          format: formData.file.name.split('.').pop() || 'unknown'
        } : undefined,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };

      onAssetCreated(newAsset);
      
      // 重置表单
      setFormData({
        name: '',
        category: MaterialCategory.Model,
        description: '',
        tags: '',
        file: null
      });
    } catch (error) {
      console.error('Failed to create asset:', error);
      alert('创建素材失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      {/* 背景遮罩 */}
      <div className="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div 
          className="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
          onClick={onClose}
        />

        {/* 模态框内容 */}
        <div className="inline-block w-full max-w-md p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white shadow-xl rounded-2xl">
          {/* 标题栏 */}
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-medium text-gray-900">
              添加新素材
            </h3>
            <button
              onClick={onClose}
              className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors duration-200"
            >
              <XMarkIcon className="h-5 w-5" />
            </button>
          </div>

          {/* 表单 */}
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* 文件上传区域 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                文件上传
              </label>
              <div
                className={`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors duration-200 ${
                  dragActive 
                    ? 'border-primary-400 bg-primary-50' 
                    : 'border-gray-300 hover:border-gray-400'
                }`}
                onDragEnter={handleDrag}
                onDragLeave={handleDrag}
                onDragOver={handleDrag}
                onDrop={handleDrop}
              >
                <input
                  type="file"
                  onChange={handleFileInputChange}
                  className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                  accept="image/*,video/*,audio/*,.txt,.md"
                />
                
                {formData.file ? (
                  <div className="flex items-center justify-center gap-2">
                    <DocumentIcon className="h-8 w-8 text-primary-600" />
                    <div>
                      <p className="text-sm font-medium text-gray-900">
                        {formData.file.name}
                      </p>
                      <p className="text-xs text-gray-500">
                        {(formData.file.size / 1024 / 1024).toFixed(2)} MB
                      </p>
                    </div>
                  </div>
                ) : (
                  <div>
                    <CloudArrowUpIcon className="mx-auto h-12 w-12 text-gray-400" />
                    <p className="mt-2 text-sm text-gray-600">
                      拖拽文件到此处或点击选择文件
                    </p>
                    <p className="text-xs text-gray-500">
                      支持图片、视频、音频和文本文件
                    </p>
                  </div>
                )}
              </div>
            </div>

            {/* 素材名称 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                素材名称 *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="输入素材名称"
                required
              />
            </div>

            {/* 素材分类 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                素材分类
              </label>
              <select
                value={formData.category}
                onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value as MaterialCategory }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              >
                {Object.values(MaterialCategory).map((category) => {
                  const config = MATERIAL_CATEGORY_CONFIG[category];
                  return (
                    <option key={category} value={category}>
                      {config.icon} {config.label}
                    </option>
                  );
                })}
              </select>
            </div>

            {/* 素材描述 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                素材描述
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent resize-none"
                placeholder="输入素材描述（可选）"
              />
            </div>

            {/* 标签 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                标签
              </label>
              <input
                type="text"
                value={formData.tags}
                onChange={(e) => setFormData(prev => ({ ...prev, tags: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="输入标签，用逗号分隔"
              />
              <p className="text-xs text-gray-500 mt-1">
                例如：时尚, 专业, 女性
              </p>
            </div>

            {/* 操作按钮 */}
            <div className="flex items-center justify-end gap-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors duration-200"
              >
                取消
              </button>
              <button
                type="submit"
                disabled={isSubmitting || !formData.name.trim()}
                className="px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-primary-500 to-primary-600 rounded-lg hover:from-primary-600 hover:to-primary-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
              >
                {isSubmitting ? '创建中...' : '创建素材'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};
