import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Loader2, Eye, EyeOff, Disc3 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useAuthStore } from '@/store/auth'
import { login as apiLogin, getCaptcha } from '@/api/system/auth'
import AIBanner from '@/components/AIBanner'
import LoginCharacters from '@/components/LoginCharacters'
import ParticleBackground from '@/components/ParticleBackground'
import Tilt from 'react-parallax-tilt'
import LampEffect from '@/components/login-effects/LampEffect'
import HackerEffect from '@/components/login-effects/HackerEffect'
import BiometricEffect from '@/components/login-effects/BiometricEffect'
import AICoreEffect from '@/components/login-effects/AICoreEffect'
import { MonitorPlay, Fingerprint, Terminal, Lightbulb, Cpu } from 'lucide-react'

export default function LoginPage() {
  const [account, setAccount] = useState('admin')
  const [password, setPassword] = useState('123456')
  const [captcha, setCaptcha] = useState('')
  const [captchaId, setCaptchaId] = useState('')
  const [captchaImg, setCaptchaImg] = useState('')
  const [showPwd, setShowPwd] = useState(false)
  const [pwdFocused, setPwdFocused] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [unlockMode, setUnlockMode] = useState<'none' | 'lamp' | 'hacker' | 'biometric' | 'ai_core'>('ai_core')
  const navigate = useNavigate()
  const loginStore = useAuthStore(s => s.login)

  const fetchCaptcha = async () => {
    try {
      const d = await getCaptcha()
      setCaptchaId(d.captchaId)
      setCaptchaImg(d.captchaImg)
    } catch { /* ignore */ }
  }

  useEffect(() => { fetchCaptcha() }, [])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!account || !password) { setError('请输入账号和密码'); return }
    setLoading(true); setError('')
    try {
      const d = await apiLogin({ account, password, captcha, captchaId })
      loginStore(d.userInfo, d.token)
      navigate('/dashboard', { replace: true })
    } catch (err: any) {
      setError(err?.message || '登录失败')
      fetchCaptcha()
    } finally { setLoading(false) }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-[#050B14] p-6 relative overflow-hidden">
      {/* AI Tech Background replacing the old dot pattern */}
      <div className="absolute inset-0 z-0">
        <AIBanner />
      </div>
      <ParticleBackground />

      {unlockMode === 'lamp' && <LampEffect onUnlock={() => setUnlockMode('none')} />}
      {unlockMode === 'hacker' && <HackerEffect onUnlock={() => setUnlockMode('none')} />}
      {unlockMode === 'biometric' && <BiometricEffect onUnlock={() => setUnlockMode('none')} />}
      {unlockMode === 'ai_core' && <AICoreEffect onUnlock={() => setUnlockMode('none')} />}

      {/* Mode Switcher Widget */}
      <div className="fixed bottom-4 left-4 z-[200] flex flex-col md:flex-row gap-2 bg-slate-900/50 backdrop-blur-md border border-white/10 p-1.5 md:p-2 rounded-2xl md:rounded-full shadow-lg text-white">
        <button onClick={() => setUnlockMode('lamp')} className={`p-2 rounded-full transition-all ${unlockMode === 'lamp' ? 'bg-emerald-500 shadow-[0_0_15px_rgba(16,185,129,0.5)]' : 'hover:bg-white/10'}`} title="暗室寻光 (Lamp)"><Lightbulb className="w-5 h-5" /></button>
        <button onClick={() => setUnlockMode('hacker')} className={`p-2 rounded-full transition-all ${unlockMode === 'hacker' ? 'bg-red-500 shadow-[0_0_15px_rgba(239,68,68,0.5)]' : 'hover:bg-white/10'}`} title="骇客入侵 (Hacker)"><Terminal className="w-5 h-5" /></button>
        <button onClick={() => setUnlockMode('biometric')} className={`p-2 rounded-full transition-all ${unlockMode === 'biometric' ? 'bg-cyan-500 shadow-[0_0_15px_rgba(6,182,212,0.5)]' : 'hover:bg-white/10'}`} title="生物解锁 (Biometric)"><Fingerprint className="w-5 h-5" /></button>
        <button onClick={() => setUnlockMode('ai_core')} className={`p-2 rounded-full transition-all ${unlockMode === 'ai_core' ? 'bg-fuchsia-500 shadow-[0_0_15px_rgba(217,70,239,0.5)]' : 'hover:bg-white/10'}`} title="神经链接 (AI Core)"><Cpu className="w-5 h-5" /></button>
        <div className="w-px h-6 bg-white/20 mx-1 hidden md:block self-center" />
        <div className="h-px w-6 bg-white/20 my-1 md:hidden self-center" />
        <button onClick={() => setUnlockMode('none')} className={`p-2 rounded-full transition-all ${unlockMode === 'none' ? 'bg-white/20' : 'hover:bg-white/10'}`} title="直接进入 (None)"><MonitorPlay className="w-5 h-5" /></button>
      </div>

      <Tilt tiltMaxAngleX={3} tiltMaxAngleY={3} scale={1.02} transitionSpeed={2500} className="relative z-10 w-full max-w-[1000px]">
        <div className="grid grid-cols-1 lg:grid-cols-2 bg-transparent rounded-[2rem] shadow-[0_0_50px_rgba(0,0,0,0.5)] overflow-hidden ring-1 ring-white/10">

        {/* Left — Characters Banner */}
        <div className="relative hidden lg:flex flex-col justify-between bg-slate-900/40 backdrop-blur-md p-10 text-white overflow-hidden">
          <div className="relative z-20 flex items-center gap-3">
            <span className="text-xl font-bold tracking-tight">Sundynix Cloud</span>
          </div>

          <div className="relative z-20 flex items-end justify-center mt-auto" style={{ height: 320 }}>
            <LoginCharacters
              isTyping={pwdFocused}
              showPassword={showPwd}
              passwordLength={password.length}
            />
          </div>

          <div className="relative z-20 mt-10 text-xs text-white/40 font-medium tracking-wide">
            © {new Date().getFullYear()} 光衍矩阵 · SUNDYNIX TECH
          </div>

          {/* Decorative blurs */}
          <div className="absolute top-0 right-0 w-[400px] h-[400px] bg-emerald-500/10 rounded-full blur-[80px] -translate-y-1/2 translate-x-1/4 pointer-events-none" />
          <div className="absolute bottom-0 left-0 w-[300px] h-[300px] bg-teal-500/10 rounded-full blur-[60px] translate-y-1/4 -translate-x-1/4 pointer-events-none" />
        </div>

        {/* Right — Login Form */}
        <div className="flex flex-col items-center justify-center px-8 py-16 sm:px-12 bg-white/95 backdrop-blur-2xl relative">
          <div className="w-full max-w-[360px]">
            {/* Mobile logo */}
            <div className="lg:hidden flex flex-col items-center justify-center gap-3 mb-10">
              <span className="text-2xl font-bold tracking-tight text-slate-900">Sundynix Console</span>
            </div>

            <div className="text-center mb-10">
              <h1 className="text-3xl font-bold tracking-tight mb-2 text-slate-900">欢迎回来！</h1>
              <p className="text-slate-500 text-sm">请输入管理员账号与密码</p>
            </div>

            <form onSubmit={handleSubmit} className="space-y-5">
              {error && (
                <div className="rounded-xl bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2 animate-fadeIn">
                  <div className="h-1.5 w-1.5 rounded-full bg-red-500" />
                  {error}
                </div>
              )}

              <div className="space-y-2">
                <Label className="text-sm font-semibold text-slate-700">账号</Label>
                <Input placeholder="请输入管理员账号" value={account}
                  onChange={e => setAccount(e.target.value)} disabled={loading}
                  className="h-12 bg-slate-50/50 border-slate-200 focus:bg-white focus:border-emerald-500 focus:ring-emerald-500/20 text-slate-900 placeholder:text-slate-400 rounded-xl transition-all" />
              </div>

              <div className="space-y-2">
                <Label className="text-sm font-semibold text-slate-700">密码</Label>
                <div className="relative">
                  <Input type={showPwd ? 'text' : 'password'} placeholder="••••••••"
                    value={password} onChange={e => setPassword(e.target.value)}
                    onFocus={() => setPwdFocused(true)} onBlur={() => setPwdFocused(false)}
                    disabled={loading}
                    className="h-12 pr-10 bg-slate-50/50 border-slate-200 focus:bg-white focus:border-emerald-500 focus:ring-emerald-500/20 text-slate-900 placeholder:text-slate-400 rounded-xl transition-all" />
                  <button type="button" onClick={() => setShowPwd(!showPwd)}
                    className="absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors" tabIndex={-1}>
                    {showPwd ? <Eye className="w-5 h-5" /> : <EyeOff className="w-5 h-5" />}
                  </button>
                </div>
              </div>

              <div className="space-y-2">
                <Label className="text-sm font-semibold text-slate-700">验证码</Label>
                <div className="flex gap-3">
                  <Input placeholder="验证码" value={captcha}
                    onChange={e => setCaptcha(e.target.value)} disabled={loading}
                    className="h-12 flex-1 bg-slate-50/50 border-slate-200 focus:bg-white focus:border-emerald-500 focus:ring-emerald-500/20 text-slate-900 placeholder:text-slate-400 rounded-xl transition-all" />
                  <div className="h-12 w-32 border border-slate-200 rounded-xl overflow-hidden cursor-pointer hover:border-slate-300 transition-colors flex items-center justify-center bg-white group relative shrink-0"
                    onClick={fetchCaptcha}>
                    {captchaImg
                      ? <img src={captchaImg} alt="captcha" className="h-full w-full object-fill" />
                      : <Disc3 className="w-5 h-5 text-slate-400 animate-spin" />}
                  </div>
                </div>
              </div>

              <Button type="submit" disabled={loading}
                className="w-full h-12 mt-4 text-base font-bold bg-emerald-600 hover:bg-emerald-700 text-white border-0 shadow-lg shadow-emerald-600/20 rounded-xl transition-all duration-300">
                {loading
                  ? <span className="flex items-center gap-2"><Loader2 className="w-5 h-5 animate-spin" />登录中...</span>
                  : '登 录'}
              </Button>
            </form>
          </div>
        </div>
      </div>
      </Tilt>
    </div>
  )
}
