import React, { useState } from 'react'
import { Upload, FolderOpen, X, Video, CheckCircle, AlertCircle, Scissors } from 'lucide-react'
import { open } from '@tauri-apps/plugin-dialog'
import { MediaService, BatchUploadResult } from '../services/mediaService'

interface VideoUploadProps {
  isOpen: boolean
  onClose: () => void
  onUploadComplete: () => void
}

const VideoUpload: React.FC<VideoUploadProps> = ({
  isOpen,
  onClose,
  onUploadComplete
}) => {
  const [uploading, setUploading] = useState(false)
  const [uploadResult, setUploadResult] = useState<BatchUploadResult | null>(null)
  const [selectedFiles, setSelectedFiles] = useState<string[]>([])
  const [selectedDirectory, setSelectedDirectory] = useState<string>('')
  const [tags, setTags] = useState<string[]>([])
  const [newTag, setNewTag] = useState('')

  if (!isOpen) return null

  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 handleUpload = async () => {
    if (selectedFiles.length === 0 && !selectedDirectory) {
      alert('请先选择文件或文件夹')
      return
    }

    setUploading(true)
    setUploadResult(null)

    try {
      if (selectedDirectory) {
        // 批量上传文件夹
        const response = await MediaService.batchUploadVideoFiles({
          source_directory: selectedDirectory,
          tags: tags.length > 0 ? tags : undefined
        })
        
        if (response.status && response.data) {
          setUploadResult(response.data)
        } else {
          alert('批量上传失败: ' + (response.msg || '未知错误'))
        }
      } else {
        // 上传单个或多个文件
        const results: BatchUploadResult = {
          total_files: selectedFiles.length,
          uploaded_files: 0,
          skipped_files: 0,
          failed_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: tags.length > 0 ? tags : undefined
            })
            
            if (response.status && response.data) {
              if (response.data.is_duplicate) {
                results.skipped_files++
                results.skipped_list.push({
                  filename: filePath.split('/').pop() || filePath,
                  reason: 'Already exists (same MD5)'
                })
              } else {
                results.uploaded_files++
                results.total_segments += response.data.segments.length
                results.uploaded_list.push(response.data)
              }
            } else {
              results.failed_files++
              results.failed_list.push({
                filename: filePath.split('/').pop() || filePath,
                error: response.msg || '未知错误'
              })
            }
          } catch (error) {
            results.failed_files++
            results.failed_list.push({
              filename: filePath.split('/').pop() || filePath,
              error: error instanceof Error ? error.message : '未知错误'
            })
          }
        }

        setUploadResult(results)
      }
    } catch (error) {
      console.error('Upload failed:', error)
      alert('上传失败: ' + (error instanceof Error ? error.message : '未知错误'))
    } finally {
      setUploading(false)
    }
  }

  const handleClose = () => {
    if (uploadResult && uploadResult.uploaded_files > 0) {
      onUploadComplete()
    }
    setSelectedFiles([])
    setSelectedDirectory('')
    setUploadResult(null)
    setTags([])
    setNewTag('')
    onClose()
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-3xl mx-4 max-h-[90vh] overflow-hidden">
        {/* 标题栏 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900 flex items-center">
            <Upload className="mr-2" size={20} />
            视频上传与分割
          </h2>
          <button
            onClick={handleClose}
            className="text-gray-400 hover:text-gray-600"
          >
            <X size={24} />
          </button>
        </div>

        {/* 内容区域 */}
        <div className="p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          {!uploadResult ? (
            <>
              {/* 选择文件方式 */}
              <div className="space-y-4">
                <h3 className="text-md font-medium text-gray-900">选择上传方式</h3>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* 选择文件 */}
                  <button
                    onClick={selectFiles}
                    disabled={uploading}
                    className="p-4 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-colors disabled:opacity-50"
                  >
                    <div className="text-center">
                      <Video className="mx-auto mb-2 text-gray-400" size={32} />
                      <p className="text-sm font-medium text-gray-900">选择视频文件</p>
                      <p className="text-xs text-gray-500">支持多选</p>
                    </div>
                  </button>

                  {/* 选择文件夹 */}
                  <button
                    onClick={selectDirectory}
                    disabled={uploading}
                    className="p-4 border-2 border-dashed border-gray-300 rounded-lg hover:border-green-400 hover:bg-green-50 transition-colors disabled:opacity-50"
                  >
                    <div className="text-center">
                      <FolderOpen className="mx-auto mb-2 text-gray-400" size={32} />
                      <p className="text-sm font-medium text-gray-900">选择文件夹</p>
                      <p className="text-xs text-gray-500">批量上传</p>
                    </div>
                  </button>
                </div>
              </div>

              {/* 标签设置 */}
              <div className="space-y-3">
                <h4 className="text-sm font-medium text-gray-900">添加标签（可选）</h4>
                
                {/* 标签输入 */}
                <div className="flex space-x-2">
                  <input
                    type="text"
                    value={newTag}
                    onChange={(e) => setNewTag(e.target.value)}
                    placeholder="输入标签名称"
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    onKeyPress={(e) => e.key === 'Enter' && addTag()}
                  />
                  <button
                    onClick={addTag}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                  >
                    添加
                  </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-blue-100 text-blue-800 text-sm rounded-full"
                      >
                        {tag}
                        <button
                          onClick={() => removeTag(tag)}
                          className="ml-2 text-blue-600 hover:text-blue-800"
                        >
                          <X size={14} />
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>

              {/* 已选择的文件/文件夹 */}
              {(selectedFiles.length > 0 || selectedDirectory) && (
                <div className="space-y-2">
                  <h4 className="text-sm font-medium text-gray-900">已选择:</h4>
                  <div className="bg-gray-50 rounded-lg p-3 max-h-32 overflow-y-auto">
                    {selectedDirectory ? (
                      <div className="text-sm text-gray-700 flex items-center">
                        <FolderOpen size={16} className="mr-2" />
                        {selectedDirectory}
                      </div>
                    ) : (
                      selectedFiles.map((file, index) => (
                        <div key={index} className="text-sm text-gray-700 flex items-center">
                          <Video size={16} className="mr-2" />
                          {file.split('/').pop()}
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}

              {/* 功能说明 */}
              <div className="bg-blue-50 rounded-lg p-4">
                <div className="flex items-start space-x-3">
                  <Scissors className="text-blue-600 mt-1" size={20} />
                  <div>
                    <h4 className="text-sm font-medium text-blue-900">智能视频分割</h4>
                    <p className="text-sm text-blue-700 mt-1">
                      上传的视频将自动按转场镜头分割成多个片段，每个片段都有独立的MD5标识、标签和使用统计。
                    </p>
                  </div>
                </div>
              </div>

              {/* 上传按钮 */}
              <div className="flex justify-end space-x-3">
                <button
                  onClick={handleClose}
                  disabled={uploading}
                  className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                >
                  取消
                </button>
                <button
                  onClick={handleUpload}
                  disabled={uploading || (selectedFiles.length === 0 && !selectedDirectory)}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center"
                >
                  {uploading ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                      处理中...
                    </>
                  ) : (
                    <>
                      <Upload size={16} className="mr-2" />
                      开始上传
                    </>
                  )}
                </button>
              </div>
            </>
          ) : (
            /* 上传结果 */
            <div className="space-y-4">
              <h3 className="text-md font-medium text-gray-900">上传结果</h3>
              
              {/* 统计信息 */}
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                <div className="text-center p-3 bg-blue-50 rounded-lg">
                  <div className="text-2xl font-bold text-blue-600">{uploadResult.total_files}</div>
                  <div className="text-sm text-blue-600">总文件数</div>
                </div>
                <div className="text-center p-3 bg-green-50 rounded-lg">
                  <div className="text-2xl font-bold text-green-600">{uploadResult.uploaded_files}</div>
                  <div className="text-sm text-green-600">成功上传</div>
                </div>
                <div className="text-center p-3 bg-purple-50 rounded-lg">
                  <div className="text-2xl font-bold text-purple-600">{uploadResult.total_segments}</div>
                  <div className="text-sm text-purple-600">生成片段</div>
                </div>
                <div className="text-center p-3 bg-yellow-50 rounded-lg">
                  <div className="text-2xl font-bold text-yellow-600">{uploadResult.skipped_files}</div>
                  <div className="text-sm text-yellow-600">跳过文件</div>
                </div>
                <div className="text-center p-3 bg-red-50 rounded-lg">
                  <div className="text-2xl font-bold text-red-600">{uploadResult.failed_files}</div>
                  <div className="text-sm text-red-600">失败文件</div>
                </div>
              </div>

              {/* 详细结果 */}
              <div className="space-y-3 max-h-64 overflow-y-auto">
                {/* 成功上传的文件 */}
                {uploadResult.uploaded_list.map((result, index) => (
                  <div key={index} className="flex items-center space-x-2 text-sm">
                    <CheckCircle size={16} className="text-green-500" />
                    <span className="text-gray-700">{result.original_video.filename}</span>
                    <span className="text-gray-500">
                      ({MediaService.formatFileSize(result.original_video.file_size)}, {result.segments.length} 片段)
                    </span>
                  </div>
                ))}

                {/* 失败的文件 */}
                {uploadResult.failed_list.map((failed, index) => (
                  <div key={index} className="flex items-center space-x-2 text-sm">
                    <AlertCircle size={16} className="text-red-500" />
                    <span className="text-gray-700">{failed.filename}</span>
                    <span className="text-red-500 text-xs">({failed.error})</span>
                  </div>
                ))}
              </div>

              {/* 关闭按钮 */}
              <div className="flex justify-end">
                <button
                  onClick={handleClose}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  完成
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default VideoUpload
