import React, { useState, useEffect } from 'react'
import { FolderOpen, File, Video, Image, Music, FileText, Download, Eye, Trash2, RefreshCw } from 'lucide-react'
import { Project } from '../services/projectService'
import { invoke } from '@tauri-apps/api/core'

interface ProjectFile {
  name: string
  path: string
  size: number
  type: 'video' | 'image' | 'audio' | 'document' | 'other'
  modified: number
  extension: string
}

interface ProjectFilesProps {
  project: Project
  files: ProjectFile[]
  onFilesChange: (files: ProjectFile[]) => void
}

const ProjectFiles: React.FC<ProjectFilesProps> = ({
  project,
  files,
  onFilesChange
}) => {
  const [loading, setLoading] = useState(false)
  const [selectedFiles, setSelectedFiles] = useState<string[]>([])
  const [sortBy, setSortBy] = useState<'name' | 'size' | 'modified'>('name')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc')

  useEffect(() => {
    loadProjectFiles()
  }, [project.local_directory])

  const loadProjectFiles = async () => {
    try {
      setLoading(true)

      // 暂时使用模拟数据，因为文件扫描功能还未完全实现
      console.log('Loading files for directory:', project.local_directory)

      // 模拟文件扫描结果
      const mockFiles: ProjectFile[] = [
        {
          name: 'project_video.mp4',
          path: `${project.local_directory}/project_video.mp4`,
          size: 15728640,
          type: 'video',
          modified: Date.now() - 86400000,
          extension: 'mp4'
        },
        {
          name: 'thumbnail.jpg',
          path: `${project.local_directory}/thumbnail.jpg`,
          size: 204800,
          type: 'image',
          modified: Date.now() - 3600000,
          extension: 'jpg'
        },
        {
          name: 'script.txt',
          path: `${project.local_directory}/script.txt`,
          size: 1024,
          type: 'document',
          modified: Date.now() - 7200000,
          extension: 'txt'
        },
        {
          name: 'audio_track.mp3',
          path: `${project.local_directory}/audio_track.mp3`,
          size: 5242880,
          type: 'audio',
          modified: Date.now() - 1800000,
          extension: 'mp3'
        },
        {
          name: 'project_notes.md',
          path: `${project.local_directory}/project_notes.md`,
          size: 2048,
          type: 'document',
          modified: Date.now() - 900000,
          extension: 'md'
        }
      ]

      onFilesChange(mockFiles)

      // TODO: 实现真实的文件扫描功能
      // try {
      //   const result = await invoke<any[]>('scan_directory', {
      //     directoryPath: project.local_directory
      //   })
      //
      //   if (result && Array.isArray(result)) {
      //     const projectFiles: ProjectFile[] = result.map(file => ({
      //       name: file.name,
      //       path: file.path,
      //       size: file.size,
      //       type: getFileType(file.extension),
      //       modified: file.modified,
      //       extension: file.extension
      //     }))
      //     onFilesChange(projectFiles)
      //   } else {
      //     onFilesChange(mockFiles)
      //   }
      // } catch (scanError) {
      //   console.warn('File scan failed, using mock data:', scanError)
      //   onFilesChange(mockFiles)
      // }

    } catch (error) {
      console.error('Failed to load project files:', error)
      onFilesChange([])
    } finally {
      setLoading(false)
    }
  }

  const getFileType = (extension: string): ProjectFile['type'] => {
    const ext = extension.toLowerCase()
    if (['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm'].includes(ext)) {
      return 'video'
    } else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) {
      return 'image'
    } else if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a'].includes(ext)) {
      return 'audio'
    } else if (['txt', 'doc', 'docx', 'pdf', 'rtf', 'md'].includes(ext)) {
      return 'document'
    } else {
      return 'other'
    }
  }

  const getFileIcon = (type: ProjectFile['type']) => {
    switch (type) {
      case 'video':
        return Video
      case 'image':
        return Image
      case 'audio':
        return Music
      case 'document':
        return FileText
      default:
        return File
    }
  }

  const formatFileSize = (bytes: number) => {
    const sizes = ['B', 'KB', 'MB', 'GB']
    if (bytes === 0) return '0 B'
    const i = Math.floor(Math.log(bytes) / Math.log(1024))
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
  }

  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const sortedFiles = [...files].sort((a, b) => {
    let comparison = 0
    
    switch (sortBy) {
      case 'name':
        comparison = a.name.localeCompare(b.name)
        break
      case 'size':
        comparison = a.size - b.size
        break
      case 'modified':
        comparison = a.modified - b.modified
        break
    }
    
    return sortOrder === 'asc' ? comparison : -comparison
  })

  const handleSort = (field: typeof sortBy) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(field)
      setSortOrder('asc')
    }
  }

  const handleFileSelect = (filePath: string) => {
    setSelectedFiles(prev => 
      prev.includes(filePath) 
        ? prev.filter(p => p !== filePath)
        : [...prev, filePath]
    )
  }

  const handleSelectAll = () => {
    if (selectedFiles.length === files.length) {
      setSelectedFiles([])
    } else {
      setSelectedFiles(files.map(f => f.path))
    }
  }

  const handleOpenFile = async (file: ProjectFile) => {
    try {
      await invoke('open_file_in_system', { filePath: file.path })
    } catch (error) {
      console.error('Failed to open file:', error)
    }
  }

  const handleDeleteFiles = async () => {
    if (selectedFiles.length === 0) return
    
    const confirmed = confirm(`确定要删除选中的 ${selectedFiles.length} 个文件吗？`)
    if (!confirmed) return

    try {
      for (const filePath of selectedFiles) {
        await invoke('delete_file', { filePath })
      }
      
      // 重新加载文件列表
      await loadProjectFiles()
      setSelectedFiles([])
    } catch (error) {
      console.error('Failed to delete files:', error)
      alert('删除文件失败')
    }
  }

  return (
    <div className="space-y-6">
      {/* 头部操作 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-medium text-gray-900">项目文件</h3>
          <p className="text-sm text-gray-600">
            项目目录：{project.local_directory}
          </p>
        </div>
        
        <div className="flex items-center space-x-2">
          {selectedFiles.length > 0 && (
            <button
              onClick={handleDeleteFiles}
              className="flex items-center px-3 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
            >
              <Trash2 size={16} className="mr-2" />
              删除选中 ({selectedFiles.length})
            </button>
          )}
          
          <button
            onClick={loadProjectFiles}
            disabled={loading}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
          >
            <RefreshCw size={16} className={`mr-2 ${loading ? 'animate-spin' : ''}`} />
            刷新
          </button>
        </div>
      </div>

      {/* 文件统计 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-blue-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-blue-600">{files.length}</div>
          <div className="text-sm text-blue-600">总文件数</div>
        </div>
        <div className="bg-green-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-green-600">
            {files.filter(f => f.type === 'video').length}
          </div>
          <div className="text-sm text-green-600">视频文件</div>
        </div>
        <div className="bg-purple-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-purple-600">
            {files.filter(f => f.type === 'image').length}
          </div>
          <div className="text-sm text-purple-600">图片文件</div>
        </div>
        <div className="bg-orange-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-orange-600">
            {formatFileSize(files.reduce((total, file) => total + file.size, 0))}
          </div>
          <div className="text-sm text-orange-600">总大小</div>
        </div>
      </div>

      {/* 文件列表 */}
      {loading ? (
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="text-gray-600 mt-2">扫描文件中...</p>
        </div>
      ) : files.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg">
          <FolderOpen className="mx-auto text-gray-400 mb-4" size={48} />
          <h3 className="text-lg font-medium text-gray-900 mb-2">项目文件夹为空</h3>
          <p className="text-gray-600">在项目目录中添加文件后点击刷新</p>
        </div>
      ) : (
        <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
          {/* 表格头部 */}
          <div className="bg-gray-50 px-6 py-3 border-b border-gray-200">
            <div className="flex items-center">
              <input
                type="checkbox"
                checked={selectedFiles.length === files.length && files.length > 0}
                onChange={handleSelectAll}
                className="mr-4"
              />
              <div className="flex-1 grid grid-cols-4 gap-4">
                <button
                  onClick={() => handleSort('name')}
                  className="text-left text-sm font-medium text-gray-700 hover:text-gray-900"
                >
                  文件名 {sortBy === 'name' && (sortOrder === 'asc' ? '↑' : '↓')}
                </button>
                <button
                  onClick={() => handleSort('size')}
                  className="text-left text-sm font-medium text-gray-700 hover:text-gray-900"
                >
                  大小 {sortBy === 'size' && (sortOrder === 'asc' ? '↑' : '↓')}
                </button>
                <button
                  onClick={() => handleSort('modified')}
                  className="text-left text-sm font-medium text-gray-700 hover:text-gray-900"
                >
                  修改时间 {sortBy === 'modified' && (sortOrder === 'asc' ? '↑' : '↓')}
                </button>
                <div className="text-sm font-medium text-gray-700">操作</div>
              </div>
            </div>
          </div>

          {/* 文件列表 */}
          <div className="divide-y divide-gray-200">
            {sortedFiles.map((file) => {
              const Icon = getFileIcon(file.type)
              return (
                <div
                  key={file.path}
                  className={`px-6 py-4 hover:bg-gray-50 transition-colors ${
                    selectedFiles.includes(file.path) ? 'bg-blue-50' : ''
                  }`}
                >
                  <div className="flex items-center">
                    <input
                      type="checkbox"
                      checked={selectedFiles.includes(file.path)}
                      onChange={() => handleFileSelect(file.path)}
                      className="mr-4"
                    />
                    <div className="flex-1 grid grid-cols-4 gap-4 items-center">
                      <div className="flex items-center">
                        <Icon size={20} className="text-gray-400 mr-3" />
                        <div>
                          <div className="font-medium text-gray-900">{file.name}</div>
                          <div className="text-sm text-gray-500">{file.extension.toUpperCase()}</div>
                        </div>
                      </div>
                      <div className="text-sm text-gray-600">
                        {formatFileSize(file.size)}
                      </div>
                      <div className="text-sm text-gray-600">
                        {formatDate(file.modified)}
                      </div>
                      <div className="flex items-center space-x-2">
                        <button
                          onClick={() => handleOpenFile(file)}
                          className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                          title="打开文件"
                        >
                          <Eye size={16} />
                        </button>
                        <button
                          onClick={() => handleOpenFile(file)}
                          className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                          title="下载文件"
                        >
                          <Download size={16} />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}

export default ProjectFiles
