import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { authAPI, filesAPI } from '@/services/api'
import { toast } from 'sonner'
import { Upload, File, Download, Trash2, LogOut, Cloud, User } from 'lucide-react'
import { getUserIdFromCookie, getUserInfoFromCookie, clearAuthCookies } from '@/utils/cookie'
import './CloudPage.css'

// Toast 显示时长常量（毫秒）
const TOAST_DURATION = 3000 // 3秒，可根据需要修改

// 文件信息类型
interface FileInfo {
  id: number
  filename: string
  original_filename: string
  file_path: string
  file_size: number
  mime_type: string
  created_at: string
  updated_at: string
}

export default function CloudPage() {
  const navigate = useNavigate()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [files, setFiles] = useState<FileInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [uploading, setUploading] = useState(false)
  const [refreshingFileId, setRefreshingFileId] = useState<number | null>(null)
  const [error, setError] = useState<string | null>(null)
  const userInfo = getUserInfoFromCookie()

  // 获取当前用户ID
  const getUserId = () => {
    const userId = getUserIdFromCookie()
    if (!userId) {
      navigate('/login')
      return null
    }
    return userId
  }

  // 更新单个文件信息
  const updateSingleFile = async (fileId: number) => {
    const userId = getUserId()
    if (!userId) return

    setRefreshingFileId(fileId)

    try {
      const response = await filesAPI.getFileInfo(fileId, userId)
      if (response.success && response.data) {
        // 更新文件列表中对应的文件信息
        setFiles(prevFiles =>
          prevFiles.map(file =>
            file.id === fileId ? response.data : file
          )
        )
      }
    } catch (error: any) {
      console.error('Update file info error:', error)
    } finally {
      setRefreshingFileId(null)
    }
  }

  // 获取用户文件列表
  const fetchFiles = async () => {
    const userId = getUserId()
    if (!userId) return

    setLoading(true)
    setError(null)

    try {
      const response = await filesAPI.getFiles(1, 100) // 获取前100个文件
      if (response.success && response.data?.files) {
        setFiles(response.data.files)
      } else {
        setError('获取文件列表失败')
      }
    } catch (error: any) {
      console.error('Fetch files error:', error)
      if (error.response?.status === 401) {
        toast.error('登录已过期，请重新登录')
        navigate('/login')
      } else {
        setError('获取文件列表失败')
      }
    } finally {
      setLoading(false)
    }
  }

  // 文件上传处理
  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    setUploading(true)
    setError(null)

    try {
      const formData = new FormData()
      formData.append('file', file)
      // 其他可选字段可以在这里添加

      const response = await filesAPI.uploadFile(formData)

      if (response.success) {
        toast.success(`文件 "${file.name}" 上传成功！`)
        // 上传成功后刷新文件列表
        setLoading(true)
        fetchFiles()
      } else {
        toast.error('文件上传失败')
      }
    } catch (error: any) {
      console.error('Upload error:', error)
      const errorMessage = error.response?.data?.detail?.message || '文件上传失败'
      toast.error(errorMessage)
    } finally {
      setUploading(false)
      // 清空文件输入框
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  // 触发文件选择
  const handleUploadClick = () => {
    fileInputRef.current?.click()
  }

  // 文件下载处理
  const handleFileDownload = async (file: FileInfo) => {
    const userId = getUserId()
    if (!userId) {
      toast.error('用户未登录')
      return
    }

    try {
      toast.loading('正在下载文件...', { duration: TOAST_DURATION })

      // 调用下载API
      const response = await filesAPI.downloadFile(file.id, userId)

      // 创建下载链接
      const blob = new Blob([response])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = file.original_filename || file.filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      toast.success(`文件 "${file.original_filename}" 下载成功！`, { duration: TOAST_DURATION })

      // 只更新单个文件信息，避免整个列表刷新
      updateSingleFile(file.id)

    } catch (error: any) {
      console.error('Download error:', error)
      let errorMessage = '下载失败'

      if (error.response?.status === 401) {
        errorMessage = '登录已过期，请重新登录'
        navigate('/login')
      } else if (error.response?.status === 403) {
        errorMessage = '没有权限下载此文件'
      } else if (error.response?.status === 404) {
        errorMessage = '文件不存在'
      } else if (error.response?.data?.detail?.message) {
        errorMessage = error.response.data.detail.message
      }

      toast.error(errorMessage)
    }
  }

  // 文件删除处理
  const handleFileDelete = async (file: FileInfo) => {
    const userId = getUserId()
    if (!userId) {
      toast.error('用户未登录')
      return
    }

    try {
      toast.loading('正在删除文件...', { duration: TOAST_DURATION })

      // 调用删除API
      const response = await filesAPI.deleteFile(file.id, userId)

      if (response.success) {
        toast.success(`文件 "${file.original_filename}" 删除成功！`, { duration: TOAST_DURATION })
        // 删除操作后需要刷新整个列表，因为文件被移除了
        fetchFiles()
      } else {
        toast.error('文件删除失败', { duration: TOAST_DURATION })
      }

    } catch (error: any) {
      console.error('Delete error:', error)
      let errorMessage = '删除失败'

      if (error.response?.status === 401) {
        errorMessage = '登录已过期，请重新登录'
        navigate('/login')
      } else if (error.response?.status === 403) {
        errorMessage = '没有权限删除此文件'
      } else if (error.response?.status === 404) {
        errorMessage = '文件不存在'
      } else if (error.response?.data?.detail?.message) {
        errorMessage = error.response.data.detail.message
      }

      toast.error(errorMessage)
    }
  }

  // 用户登出处理
  const handleLogout = async () => {
    try {
      // 调用登出API
      await authAPI.logout()
      toast.success('登出成功！')
    } catch (error: any) {
      console.error('Logout error:', error)
      // 即使API调用失败，也要清除本地数据
      toast.error('登出成功！')
    } finally {
      // 清除本地存储的用户信息
      clearAuthCookies()
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user')

      // 跳转到登录页面
      navigate('/login')
    }
  }

  // 组件加载时检查用户状态并获取文件列表
  useEffect(() => {
    // 检查用户是否已登录
    if (!userInfo) {
      navigate('/login')
      return
    }
    fetchFiles()
  }, [])

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN')
  }

  // 获取文件图标样式类
  const getFileIconClass = (mimeType: string) => {
    if (mimeType.startsWith('image/')) {
      return 'image'
    } else if (mimeType.startsWith('video/')) {
      return 'video'
    } else if (mimeType.startsWith('audio/')) {
      return 'audio'
    } else if (mimeType.includes('pdf')) {
      return 'pdf'
    } else if (mimeType.includes('zip') || mimeType.includes('rar')) {
      return 'archive'
    } else {
      return 'default'
    }
  }

  return (
    <div className="cloud-page-container">
      <div className="cloud-main-container">
        <div className="cloud-content">
          {/* 页面标题 */}
          <div className="cloud-header">
            <Cloud className="h-12 w-12 text-primary mx-auto mb-4" style={{ color: '#667eea' }} />
            <h1>云盘文件管理</h1>
            <p className="text-gray-600">管理您的云盘文件</p>
          </div>

          {/* 用户信息 */}
          {userInfo && (
            <div className="user-info">
              <User className="h-4 w-4 text-gray-600" />
              <span>欢迎，{userInfo.username}</span>
              <span>|</span>
              <span>存储空间：{formatFileSize(userInfo.storage_used || 0)} / {formatFileSize(userInfo.storage_quota || 104857600)}</span>
            </div>
          )}

          {/* 上传按钮 */}
          <div className="upload-section">
            <input
              ref={fileInputRef}
              type="file"
              onChange={handleFileUpload}
              className="hidden"
              disabled={uploading}
            />
            <button
              onClick={handleUploadClick}
              disabled={uploading}
              className="upload-btn"
            >
              {uploading ? (
                <>
                  <div className="loading-spinner"></div>
                  <span>上传中...</span>
                </>
              ) : (
                <>
                  <Upload className="h-4 w-4" />
                  <span>上传文件</span>
                </>
              )}
            </button>
          </div>

          {/* 文件列表 */}
          <div className="files-table-container">
            {loading ? (
              <div className="loading-state">
                <i className="fas fa-cloud"></i>
                <h3>加载中...</h3>
                <p>正在获取您的文件列表</p>
              </div>
            ) : error ? (
              <div className="error-state">
                <i className="fas fa-exclamation-triangle"></i>
                <h3>加载失败</h3>
                <p>{error}</p>
                <button onClick={fetchFiles} className="retry-btn">
                  重新加载
                </button>
              </div>
            ) : files.length === 0 ? (
              <div className="empty-state">
                <i className="fas fa-folder-open"></i>
                <h3>暂无文件</h3>
                <p>您的云盘还是空的，使用上方按钮上传第一个文件吧！</p>
              </div>
            ) : (
              <table className="files-table">
                <thead>
                  <tr>
                    <th>文件名</th>
                    <th>原始文件名</th>
                    <th>大小</th>
                    <th>类型</th>
                    <th>修改时间</th>
                    <th style={{ textAlign: 'right' }}>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {files.map((file) => (
                    <tr key={file.id}>
                      <td>
                        <div className="file-name">
                          <div className={`file-icon ${getFileIconClass(file.mime_type)}`}>
                            <File className="h-4 w-4" />
                          </div>
                          <span>{file.filename}</span>
                        </div>
                      </td>
                      <td>
                        <span className="file-original-name">{file.original_filename}</span>
                      </td>
                      <td>
                        <span className="file-size">{formatFileSize(file.file_size)}</span>
                      </td>
                      <td>
                        <span className="file-type">
                          {file.mime_type.split('/')[1]?.toUpperCase() || 'FILE'}
                        </span>
                      </td>
                      <td>
                        <span className="file-date">{formatDate(file.updated_at)}</span>
                      </td>
                      <td>
                        <div className="action-buttons">
                          <button
                            className="action-btn download"
                            onClick={() => handleFileDownload(file)}
                            title="下载文件"
                            disabled={refreshingFileId === file.id}
                          >
                            {refreshingFileId === file.id ? (
                              <div className="loading-spinner"></div>
                            ) : (
                              <Download className="h-4 w-4" />
                            )}
                          </button>
                          <button
                            className="action-btn delete"
                            onClick={() => handleFileDelete(file)}
                            title="删除文件"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}