import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { authAPI, filesAPI } from '@/services/api'
import { toast } from 'sonner'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Button } from '@/components/ui/button'
import { Cloud, Upload, File, Folder, Download, Trash2, User } from 'lucide-react'
import { getUserIdFromCookie, getUserInfoFromCookie } from '@/utils/cookie'

// 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)
    }
  }

  // 组件加载时检查用户状态并获取文件列表
  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 getFileIcon = (mimeType: string) => {
    if (mimeType.startsWith('image/')) {
      return <File className="h-4 w-4 text-green-600" />
    } else if (mimeType.startsWith('video/')) {
      return <File className="h-4 w-4 text-blue-600" />
    } else if (mimeType.startsWith('audio/')) {
      return <File className="h-4 w-4 text-purple-600" />
    } else if (mimeType.includes('pdf')) {
      return <File className="h-4 w-4 text-red-600" />
    } else if (mimeType.includes('zip') || mimeType.includes('rar')) {
      return <File className="h-4 w-4 text-yellow-600" />
    } else {
      return <File className="h-4 w-4 text-gray-600" />
    }
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            云盘文件管理
          </h1>
          <p className="text-gray-600">管理您的云盘文件</p>
        </div>
      </div>

      {/* 上传按钮 */}
      <div className="mb-6">
        <input
          ref={fileInputRef}
          type="file"
          onChange={handleFileUpload}
          className="hidden"
          disabled={uploading}
        />

      </div>

      {/* 文件列表 */}
      <div className="bg-white rounded-lg border border-gray-200">
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <Cloud className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600">加载中...</p>
            </div>
          </div>
        ) : error ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <p className="text-red-600 mb-4">{error}</p>
              <Button onClick={fetchFiles} variant="outline">
                重新加载
              </Button>
            </div>
          </div>
        ) : files.length === 0 ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <Cloud className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600 mb-4">暂无文件，请上传</p>
              <Button
                onClick={handleUploadClick}
                disabled={uploading}
                className="flex items-center space-x-2 mx-auto"
              >
                <Upload className="h-4 w-4" />
                <span>{uploading ? '上传中...' : '上传文件'}</span>
              </Button>
            </div>
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>文件名</TableHead>
                <TableHead>文件中文名</TableHead>
                <TableHead>大小</TableHead>
                <TableHead>类型</TableHead>
                <TableHead>修改时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {files.map((file) => (
                <TableRow key={file.id}>
                  <TableCell className="font-medium">
                    <div className="flex items-center space-x-2">
                      {getFileIcon(file.mime_type)}
                      <span>{file.filename}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="text-blue-600 font-medium">{file.original_filename}</span>
                  </TableCell>
                  <TableCell>{formatFileSize(file.file_size)}</TableCell>
                  <TableCell>
                    <span className="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800">
                      {file.mime_type.split('/')[1]?.toUpperCase() || 'FILE'}
                    </span>
                  </TableCell>
                  <TableCell className="text-gray-600">
                    {formatDate(file.updated_at)}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end space-x-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleFileDownload(file)}
                        title="下载文件"
                        disabled={refreshingFileId === file.id}
                      >
                        {refreshingFileId === file.id ? (
                          <div className="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-blue-600" />
                        ) : (
                          <Download className="h-4 w-4" />
                        )}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleFileDelete(file)}
                        className="text-red-600 hover:text-red-700 hover:bg-red-50"
                        title="删除文件"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </div>
    </div>
  )
}