import React, { useState } from 'react'
import { Upload, FolderOpen, X, Music, CheckCircle, AlertCircle } from 'lucide-react'
import { open } from '@tauri-apps/plugin-dialog'
import { AudioService, BatchUploadResult } from '../services/audioService'

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

const AudioUpload: React.FC<AudioUploadProps> = ({
  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>('')

  if (!isOpen) return null

  const selectFiles = async () => {
    try {
      const files = await open({
        multiple: true,
        title: '选择音频文件',
        filters: [
          {
            name: '音频文件',
            extensions: ['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma']
          }
        ]
      })
      
      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 handleUpload = async () => {
    if (selectedFiles.length === 0 && !selectedDirectory) {
      alert('请先选择文件或文件夹')
      return
    }

    setUploading(true)
    setUploadResult(null)

    try {
      if (selectedDirectory) {
        // 批量上传文件夹
        const response = await AudioService.batchUploadAudioFiles({
          source_directory: selectedDirectory
        })
        
        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,
          uploaded_list: [],
          skipped_list: [],
          failed_list: []
        }

        for (const filePath of selectedFiles) {
          try {
            const response = await AudioService.uploadAudioFile({
              source_path: filePath
            })
            
            if (response.status && response.data) {
              results.uploaded_files++
              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)
    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-2xl 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">
                      <Music 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>

              {/* 已选择的文件/文件夹 */}
              {(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">
                        📁 {selectedDirectory}
                      </div>
                    ) : (
                      selectedFiles.map((file, index) => (
                        <div key={index} className="text-sm text-gray-700">
                          🎵 {file.split('/').pop()}
                        </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-4 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-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((audio, 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">{audio.filename}</span>
                    <span className="text-gray-500">({AudioService.formatFileSize(audio.file_size)})</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 AudioUpload
