import { Link, useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { Cloud, Eye, EyeOff } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { authAPI } from '@/services/api'
import { toast } from 'sonner'
import { setUserInfoInCookie, setTokenInCookie, deleteCookie } from '@/utils/cookie'
import '@/styles/auth.css'

export default function LoginPage() {
  const navigate = useNavigate()
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!formData.username || !formData.password) {
      toast.error('请填写用户名和密码')
      return
    }

    setIsLoading(true)

    try {
      const response = await authAPI.login({
        username: formData.username,
        password: formData.password
      })

      if (response.success) {
        // 保存用户信息到cookie
        if (response.data?.user) {
          setUserInfoInCookie(response.data.user)
        }

        // 保存JWT token到cookie
        if (response.data?.tokens?.access_token) {
          setTokenInCookie(response.data.tokens.access_token)
          // 同时也保存到localStorage作为备份
          localStorage.setItem('access_token', response.data.tokens.access_token)
        }
        if (response.data?.tokens?.refresh_token) {
          localStorage.setItem('refresh_token', response.data.tokens.refresh_token)
        }

        toast.success('登录成功！正在跳转...')

        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          navigate('/cloud')
        }, 1000)
      } else {
        toast.error(response.detail?.message || '登录失败')
      }
    } catch (error: any) {
      console.error('Login error:', error)

      // 尝试从错误响应中提取具体错误信息
      let errorMessage = '登录失败，请稍后重试'

      if (error.response?.data) {
        const errorData = error.response.data
        if (errorData.detail?.message) {
          errorMessage = errorData.detail.message
        } else if (errorData.detail?.code) {
          // 根据错误码显示更友好的消息
          switch (errorData.detail.code) {
            case 'INVALID_CREDENTIALS':
              errorMessage = '用户名或密码错误'
              break
            case 'USER_NOT_FOUND':
              errorMessage = '用户不存在'
              break
            default:
              errorMessage = errorData.detail.message || '登录失败'
          }
        }
      }

      toast.error(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-cyan-50 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0">
        <div className="absolute top-0 -left-4 w-72 h-72 bg-blue-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob"></div>
        <div className="absolute top-0 -right-4 w-72 h-72 bg-cyan-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-2000"></div>
        <div className="absolute -bottom-8 left-20 w-72 h-72 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-4000"></div>
        <div className="absolute bottom-0 right-20 w-72 h-72 bg-sky-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-6000"></div>
      </div>

      <div className="relative min-h-screen flex items-center justify-center px-4">
        <div className="max-w-md w-full">
          <div className="text-center mb-8">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-blue-500 to-cyan-600 rounded-2xl mb-4 shadow-lg">

            </div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">登录账户</h1>
            <p className="text-gray-600">
              欢迎回来！请登录您的账户
            </p>
          </div>

          <div className="bg-white/80 backdrop-blur-xl rounded-2xl shadow-xl border border-white/20 p-8">
            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  用户名或邮箱
                </label>
                <div className="relative">
                  <input
                    type="text"
                    className="w-full px-4 py-3 bg-white/50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 backdrop-blur-sm"
                    placeholder="请输入用户名或邮箱"
                    value={formData.username}
                    onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  密码
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    className="w-full px-4 py-3 pr-12 bg-white/50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 backdrop-blur-sm"
                    placeholder="请输入密码"
                    value={formData.password}
                    onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                    required
                  />
                  <button
                    type="button"
                    className="absolute right-3 top-3.5 text-gray-400 hover:text-gray-600 transition-colors duration-200"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                  </button>
                </div>
              </div>

              <Button
                type="submit"
                className="w-full bg-gradient-to-r from-blue-500 to-cyan-600 hover:from-blue-600 hover:to-cyan-700 text-white font-medium py-3 rounded-lg transition-all duration-200 transform hover:scale-[1.02] shadow-lg"
                disabled={isLoading}
              >
                {isLoading ? (
                  <div className="flex items-center justify-center">
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                    登录中...
                  </div>
                ) : (
                  '登录'
                )}
              </Button>
            </form>

            <div className="mt-8 text-center">
              <p className="text-sm text-gray-600">
                还没有账户？{' '}
                <Link
                  to="/register"
                  className="text-blue-600 hover:text-blue-700 font-medium hover:underline transition-colors duration-200"
                >
                  立即注册
                </Link>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}