import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { Heart, Star, Cloud, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import logo from "@/assets/logo.png"

export default function Login() {
  const [isRegister, setIsRegister] = useState(false)
  const [showPasswordLogin, setShowPasswordLogin] = useState(false)
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [oauthEnabled, setOauthEnabled] = useState(false)
  const navigate = useNavigate()

  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    const oauthEmail = params.get('email')
    const oauthStatus = params.get('oauth')
    if (oauthStatus === 'success' && oauthEmail) {
      const loadProfile = async () => {
        let hasCode = false
        try {
          const res = await fetch(`/api/auth/profile?email=${encodeURIComponent(oauthEmail)}`)
          if (res.ok) {
            const data = await res.json()
            hasCode = Boolean(data?.user?.hasCode)
          }
        } catch {
          hasCode = false
        }
        const user = { email: oauthEmail, auth_provider: 'authentik', hasCode }
        localStorage.setItem('farm_user', JSON.stringify(user))
        localStorage.removeItem('farm_code')
        navigate("/dashboard")
      }
      loadProfile()
      return
    }
    if (params.get('error') === 'oauth_failed') {
      setError("OAuth 登录失败，请重试")
    }
  }, [navigate])

  useEffect(() => {
    let cancelled = false
    fetch('/api/auth/oauth/status')
      .then((res) => res.json())
      .then((data) => {
        if (!cancelled) setOauthEnabled(Boolean(data?.enabled))
      })
      .catch(() => {
        if (!cancelled) setOauthEnabled(false)
      })
    return () => {
      cancelled = true
    }
  }, [])

  const handleOAuthLogin = () => {
    window.location.href = '/api/auth/oauth/authentik';
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!email || !password) return
    if (isRegister && password !== confirmPassword) {
      setError("两次输入的密码不一致")
      return
    }

    setIsLoading(true)
    setError("")

    try {
      const endpoint = isRegister ? '/api/auth/register' : '/api/auth/login'
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || (isRegister ? '注册失败' : '登录失败'))
      }

      // Save user info to localStorage
      localStorage.setItem('farm_user', JSON.stringify(data.user))
      // Clear old code if exists
      localStorage.removeItem('farm_code')
      
      navigate("/dashboard")
    } catch (err) {
      const message = err instanceof Error ? err.message : '出错了'
      setError(message || '出错了')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-pink-50 to-purple-50 p-4 overflow-hidden relative">
      {/* Decorative Background Elements */}
      <div className="absolute top-20 left-20 text-blue-200 animate-bounce delay-1000 duration-3000">
        <Cloud size={64} fill="currentColor" className="opacity-50" />
      </div>
      <div className="absolute bottom-40 right-20 text-pink-200 animate-pulse delay-700">
        <Heart size={48} fill="currentColor" className="opacity-50" />
      </div>
      <div className="absolute top-1/3 right-1/4 text-yellow-100 animate-spin-slow">
        <Star size={32} fill="currentColor" className="opacity-60" />
      </div>

      <Card className="w-full max-w-md relative z-10 border-white/50 bg-white/80 backdrop-blur-sm shadow-[0_8px_30px_rgb(0,0,0,0.04)] rounded-3xl overflow-hidden transition-all duration-500">
        <div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-blue-200 via-pink-200 to-purple-200"></div>
        
        <CardHeader className="text-center pt-10 pb-2">
          <div className="mx-auto p-2 rounded-full w-24 h-24 flex items-center justify-center mb-4 transition-transform hover:scale-105 duration-300">
            <img src={logo} alt="Logo" className="h-full w-full object-contain drop-shadow-sm" />
          </div>
          <CardTitle className="text-3xl font-bold text-slate-700 tracking-tight">
            {isRegister ? '加入谢尔达莱群岛' : '谢尔达莱群岛'}
          </CardTitle>
          <CardDescription className="text-slate-500 mt-2">
            {isRegister ? '开启你的田园生活' : '欢迎回到你的温馨农场'} <br/>
            <span className="text-xs text-pink-400">今天也要种出美好的事物哦</span>
          </CardDescription>
        </CardHeader>
        
        <form onSubmit={handleSubmit}>
          <CardContent className="space-y-6 pt-6">
            <div className="space-y-4">
              {oauthEnabled && (
                <Button 
                  type="button" 
                  onClick={handleOAuthLogin}
                  className="w-full h-12 text-lg rounded-2xl bg-gradient-to-r from-blue-300 to-pink-300 hover:from-blue-400 hover:to-pink-400 text-white border-0 shadow-lg shadow-blue-100 transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]"
                >
                  <div className="flex items-center gap-2">
                    <span className="text-base">使用猹ID登录</span>
                  </div>
                </Button>
              )}

              <button
                type="button"
                onClick={() => {
                  setShowPasswordLogin(!showPasswordLogin)
                  setError("")
                }}
                className="w-full text-sm text-slate-400 hover:text-slate-600 font-medium transition-colors"
              >
                {showPasswordLogin ? '收起账号密码登录' : '使用账号密码登录'}
              </button>

              {showPasswordLogin && (
                <div className="space-y-4 pt-2 animate-in slide-in-from-top-2 fade-in duration-300">
                  <div className="space-y-2">
                    <Input 
                      type="email"
                      placeholder="邮箱" 
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      disabled={isLoading}
                      className="h-12 text-center text-lg bg-slate-50/50 border-slate-100 focus:border-blue-200 focus:ring-blue-100 rounded-2xl transition-all duration-300 hover:bg-white"
                    />
                    <Input 
                      type="password"
                      placeholder="密码" 
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      disabled={isLoading}
                      className="h-12 text-center text-lg bg-slate-50/50 border-slate-100 focus:border-blue-200 focus:ring-blue-100 rounded-2xl transition-all duration-300 hover:bg-white"
                    />
                    {isRegister && (
                      <Input 
                        type="password"
                        placeholder="确认密码" 
                        value={confirmPassword}
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        disabled={isLoading}
                        className="h-12 text-center text-lg bg-slate-50/50 border-slate-100 focus:border-blue-200 focus:ring-blue-100 rounded-2xl transition-all duration-300 hover:bg-white animate-in slide-in-from-top-2 fade-in duration-300"
                      />
                    )}
                  </div>
                  {error && (
                    <div className="text-center text-sm text-red-400 bg-red-50 py-2 rounded-lg animate-in fade-in slide-in-from-top-1">
                      {error}
                    </div>
                  )}
                  <Button 
                    type="submit" 
                    className="w-full h-12 text-lg rounded-2xl bg-gradient-to-r from-blue-300 to-pink-300 hover:from-blue-400 hover:to-pink-400 text-white border-0 shadow-lg shadow-blue-100 transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]"
                    disabled={isLoading}
                  >
                    {isLoading ? (
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                    ) : (
                      isRegister ? '注册账号' : '立即登录'
                    )}
                  </Button>

                  <div className="flex items-center justify-center gap-2 text-sm text-slate-400">
                    <span>{isRegister ? '已有账号？' : '还没有账号？'}</span>
                    <button
                      type="button"
                      onClick={() => {
                        setIsRegister(!isRegister)
                        setError("")
                        setConfirmPassword("")
                      }}
                      className="text-blue-400 hover:text-blue-500 font-medium transition-colors hover:underline"
                    >
                      {isRegister ? '直接登录' : '注册一个'}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
          <CardFooter className="flex flex-col gap-4 pb-8" />
        </form>
      </Card>
      
      <div className="absolute bottom-4 text-slate-300 text-sm font-light">
        专为 Karriis 设计 🌸
      </div>
    </div>
  )
}
