/**
 * 导入素材模态框组件
 * 参考素材管理页面设计，支持选择目录、模特和自动分镜配置
 */

import React, { useState } from 'react'
import { X, Upload, FolderOpen, Users, Scissors, Video, CheckCircle, Plus, Trash2 } from 'lucide-react'
import { open } from '@tauri-apps/plugin-dialog'
import { Project } from '../services/projectService'
import { Model } from '../services/modelService'
import { MediaService, BatchUploadResult } from '../services/mediaService'

interface ImportMaterialModalProps {
  project: Project
  models: Model[]
  onConfirm: (result: BatchUploadResult) => void
  onCancel: () => void
}

const ImportMaterialModal: React.FC<ImportMaterialModalProps> = ({
  project,
  models,
  onConfirm,
  onCancel
}) => {
  const [uploading, setUploading] = useState(false)
  const [uploadResult, setUploadResult] = useState<BatchUploadResult | null>(null)
  const [selectedFiles, setSelectedFiles] = useState<string[]>([])
  const [selectedDirectory, setSelectedDirectory] = useState<string>('')
  const [selectedModelIds, setSelectedModelIds] = useState<string[]>([])
  const [tags, setTags] = useState<string[]>([])
  const [newTag, setNewTag] = useState('')
  const [enableAutoSegmentation, setEnableAutoSegmentation] = useState(true)

  // 选择文件
  const selectFiles = async () => {
    try {
      const files = await open({
        multiple: true,
        title: '选择视频文件',
        filters: [
          {
            name: '视频文件',
            extensions: ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm', 'm4v']
          }
        ]
      })
      
      if (files && Array.isArray(files)) {
        setSelectedFiles(files)
        setSelectedDirectory('')
      }
    } catch (error) {
      console.error('Failed to select files:', error)
    }
  }

  // 选择目录
  const selectDirectory = async () => {
    try {
      const directory = await open({
        directory: true,
        multiple: false,
        title: '选择视频文件夹'
      })
      
      if (directory && typeof directory === 'string') {
        setSelectedDirectory(directory)
        setSelectedFiles([])
      }
    } catch (error) {
      console.error('Failed to select directory:', error)
    }
  }

  // 添加标签
  const addTag = () => {
    if (newTag.trim() && !tags.includes(newTag.trim())) {
      setTags([...tags, newTag.trim()])
      setNewTag('')
    }
  }

  // 移除标签
  const removeTag = (tagToRemove: string) => {
    setTags(tags.filter(tag => tag !== tagToRemove))
  }

  // 处理导入
  const handleImport = async () => {
    if (selectedFiles.length === 0 && !selectedDirectory) {
      alert('请先选择文件或文件夹')
      return
    }

    setUploading(true)
    setUploadResult(null)

    try {
      // 准备导入参数
      const importTags = [...tags]

      console.log('开始导入素材到项目:', project)
      console.log('初始标签:', importTags)

      // 添加项目标签
      if (project.product_name && !importTags.includes(project.product_name)) {
        importTags.push(project.product_name)
        console.log('添加项目标签:', project.product_name)
      }

      // 添加模特标签
      const selectedModels = models.filter(m => selectedModelIds.includes(m.id))
      selectedModels.forEach(model => {
        if (!importTags.includes(model.model_number)) {
          importTags.push(model.model_number)
          console.log('添加模特标签:', model.model_number)
        }
      })

      console.log('最终标签列表:', importTags)

      let result: BatchUploadResult

      if (selectedDirectory) {
        // 批量导入文件夹
        const response = await MediaService.batchUploadVideoFiles({
          source_directory: selectedDirectory,
          tags: importTags.length > 0 ? importTags : undefined
        })
        
        if (response.status && response.data) {
          result = response.data
        } else {
          throw new Error(response.msg || '批量导入失败')
        }
      } else {
        // 导入单个或多个文件
        result = {
          total_files: selectedFiles.length,
          uploaded_files: 0,
          failed_files: 0,
          skipped_files: 0,
          total_segments: 0,
          uploaded_list: [],
          skipped_list: [],
          failed_list: []
        }

        for (const filePath of selectedFiles) {
          try {
            const response = await MediaService.uploadVideoFile({
              source_path: filePath,
              tags: importTags
            })

            if (response.status && response.data) {
              result.uploaded_files++
              result.total_segments += response.data.segments.length
              result.uploaded_list.push(response.data)
            } else {
              result.failed_files++
              result.failed_list.push({
                filename: filePath.split('/').pop() || filePath,
                error: response.msg || '上传失败'
              })
            }
          } catch (error) {
            result.failed_files++
            result.failed_list.push({
              filename: filePath.split('/').pop() || filePath,
              error: String(error)
            })
          }
        }
      }

      setUploadResult(result)
      
      // 如果有成功的上传，调用完成回调
      if (result.uploaded_files > 0) {
        onConfirm(result)
      }

    } catch (error) {
      console.error('Import failed:', error)
      alert('导入失败: ' + (error instanceof Error ? error.message : '未知错误'))
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* 标题栏 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">导入素材</h2>
            <p className="text-sm text-gray-600">为项目 "{project.name}" 导入视频素材</p>
          </div>
          <button
            onClick={onCancel}
            className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        <div className="p-6 space-y-6">
          {/* 文件选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">选择素材</label>
            <div className="grid grid-cols-2 gap-3">
              <button
                onClick={selectFiles}
                disabled={uploading}
                className="flex flex-col items-center justify-center p-6 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors disabled:opacity-50"
              >
                <Video className="w-8 h-8 text-gray-400 mb-2" />
                <span className="text-sm font-medium text-gray-700">选择文件</span>
                <span className="text-xs text-gray-500">支持多选视频文件</span>
              </button>

              <button
                onClick={selectDirectory}
                disabled={uploading}
                className="flex flex-col items-center justify-center p-6 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors disabled:opacity-50"
              >
                <FolderOpen className="w-8 h-8 text-gray-400 mb-2" />
                <span className="text-sm font-medium text-gray-700">选择文件夹</span>
                <span className="text-xs text-gray-500">批量导入整个文件夹</span>
              </button>
            </div>

            {/* 显示选择的文件或目录 */}
            {selectedFiles.length > 0 && (
              <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-center text-blue-700">
                  <CheckCircle className="w-4 h-4 mr-2" />
                  <span className="text-sm font-medium">已选择 {selectedFiles.length} 个文件</span>
                </div>
              </div>
            )}

            {selectedDirectory && (
              <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-center text-blue-700">
                  <CheckCircle className="w-4 h-4 mr-2" />
                  <span className="text-sm font-medium">已选择文件夹</span>
                </div>
                <div className="text-xs text-blue-600 mt-1 truncate">{selectedDirectory}</div>
              </div>
            )}
          </div>

          {/* 模特选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              <Users className="w-4 h-4 inline mr-1" />
              关联模特（可选）
            </label>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3 max-h-32 overflow-y-auto">
              {models.map((model) => (
                <label key={model.id} className="flex items-center">
                  <input
                    type="checkbox"
                    checked={selectedModelIds.includes(model.id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedModelIds([...selectedModelIds, model.id])
                      } else {
                        setSelectedModelIds(selectedModelIds.filter(id => id !== model.id))
                      }
                    }}
                    disabled={uploading}
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">{model.model_number}</span>
                </label>
              ))}
            </div>
          </div>

          {/* 标签设置 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">标签（可选）</label>
            <div className="flex items-center space-x-2 mb-3">
              <input
                type="text"
                value={newTag}
                onChange={(e) => setNewTag(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && addTag()}
                placeholder="输入标签名称"
                disabled={uploading}
                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <button
                onClick={addTag}
                disabled={!newTag.trim() || uploading}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              >
                <Plus size={16} />
              </button>
            </div>
            
            {tags.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {tags.map((tag, index) => (
                  <span
                    key={index}
                    className="inline-flex items-center px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm"
                  >
                    {tag}
                    <button
                      onClick={() => removeTag(tag)}
                      disabled={uploading}
                      className="ml-2 text-gray-500 hover:text-gray-700 disabled:opacity-50"
                    >
                      <Trash2 size={12} />
                    </button>
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* 自动分镜设置 */}
          <div>
            <label className="flex items-center mb-3">
              <input
                type="checkbox"
                checked={enableAutoSegmentation}
                onChange={(e) => setEnableAutoSegmentation(e.target.checked)}
                disabled={uploading}
                className="mr-2"
              />
              <Scissors className="w-4 h-4 mr-1" />
              <span className="text-sm font-medium text-gray-700">启用自动分镜</span>
            </label>
            <p className="text-xs text-gray-500 ml-6">
              自动将长视频分割成多个片段，便于后续编辑使用
            </p>
          </div>

          {/* 上传结果 */}
          {uploadResult && (
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center text-green-700 mb-2">
                <CheckCircle className="w-5 h-5 mr-2" />
                <span className="font-medium">导入完成</span>
              </div>
              <div className="text-sm text-green-600 space-y-1">
                <div>总文件数: {uploadResult.total_files}</div>
                <div>成功导入: {uploadResult.uploaded_files}</div>
                <div>失败: {uploadResult.failed_files}</div>
                <div>跳过: {uploadResult.skipped_files}</div>
                <div>生成片段: {uploadResult.total_segments}</div>
              </div>
              {uploadResult.failed_list.length > 0 && (
                <div className="mt-2">
                  <div className="text-sm font-medium text-red-700">错误信息:</div>
                  <div className="text-xs text-red-600 max-h-20 overflow-y-auto">
                    {uploadResult.failed_list.map((error, index) => (
                      <div key={index}>• {error.filename}: {error.error}</div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200">
          <button
            onClick={onCancel}
            disabled={uploading}
            className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
          >
            {uploadResult ? '关闭' : '取消'}
          </button>

          <button
            onClick={handleImport}
            disabled={uploading || (selectedFiles.length === 0 && !selectedDirectory)}
            className="flex items-center px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            {uploading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                导入中...
              </>
            ) : (
              <>
                <Upload className="w-4 h-4 mr-2" />
                开始导入
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  )
}

export default ImportMaterialModal
