'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import { useTranslation } from 'react-i18next'
import { ShieldCheck, Sparkles, Lock, User } from 'lucide-react'
import { useAuth } from '@/contexts/AuthContext'
import { toast } from 'sonner'
import heroImage from '@/assets/login-hero.jpg'

function Particle({ style }: { style: React.CSSProperties }) {
  return <div className="particle" style={style} />
}

const particles = Array.from({ length: 12 }, (_, i) => ({
  id: i,
  style: {
    width: `${4 + (i % 5) * 3}px`,
    height: `${4 + (i % 5) * 3}px`,
    left: `${8 + ((i * 7.5) % 85)}%`,
    bottom: `${5 + ((i * 11) % 40)}%`,
    background:
      i % 3 === 0
        ? 'rgba(212,160,84,0.7)'
        : i % 3 === 1
          ? 'rgba(61,139,110,0.6)'
          : 'rgba(139,197,173,0.5)',
    animationDuration: `${4 + ((i * 1.3) % 5)}s`,
    animationDelay: `${(i * 0.6) % 4}s`,
  } as React.CSSProperties,
}))

export function LoginPage() {
  const { t } = useTranslation()
  const { login, user, loading } = useAuth()
  const router = useRouter()
  const [email, setEmail] = useState('admin@ekgroup.com')
  const [password, setPassword] = useState('password')
  const [submitting, setSubmitting] = useState(false)
  const [focused, setFocused] = useState<string | null>(null)

  useEffect(() => {
    if (!loading && user) {
      router.replace('/')
    }
  }, [loading, user, router])

  if (loading || user) {
    return (
      <div
        className="flex h-screen items-center justify-center overflow-hidden"
        style={{ background: 'linear-gradient(135deg, #0a1510 0%, #14291f 100%)' }}
      >
        <div className="h-10 w-10 animate-spin rounded-full border-2 border-brand-500 border-t-transparent" />
      </div>
    )
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)
    try {
      await login(email, password)
      toast.success(t('auth.welcome'))
      router.replace('/')
    } catch {
      toast.error(t('login.invalidCredentials'))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="premium-page-bg flex h-screen overflow-hidden">
      <div className="mesh-grid-bg pointer-events-none absolute inset-0" />

      {/* ===== LEFT PANEL ===== */}
      <div
        className="premium-card relative m-4 hidden h-[calc(100%-2rem)] w-[52%] flex-col overflow-hidden rounded-3xl lg:flex"
        style={{ background: 'linear-gradient(150deg, #0f2418 0%, #0a1a10 60%, #060e09 100%)' }}
      >
        <div className="animate-rotate-ring pointer-events-none absolute left-1/2 top-1/2 h-[560px] w-[560px] -translate-x-1/2 -translate-y-1/2 rounded-full border border-brand-500/10" />
        <div className="animate-rotate-ring-rev pointer-events-none absolute left-1/2 top-1/2 h-[420px] w-[420px] -translate-x-1/2 -translate-y-1/2 rounded-full border border-dashed border-accent-400/10" />
        <div
          className="animate-rotate-ring pointer-events-none absolute left-1/2 top-1/2 h-[700px] w-[700px] -translate-x-1/2 -translate-y-1/2 rounded-full border border-brand-700/5"
          style={{ animationDuration: '30s' }}
        />

        <div
          className="glow-pulse pointer-events-none absolute -top-32 left-1/4 h-72 w-72 rounded-full blur-3xl"
          style={{ background: 'radial-gradient(circle, rgba(61,139,110,0.35), transparent 70%)' }}
        />
        <div
          className="glow-pulse pointer-events-none absolute -bottom-24 right-1/4 h-64 w-64 rounded-full blur-3xl"
          style={{
            background: 'radial-gradient(circle, rgba(212,160,84,0.28), transparent 70%)',
            animationDelay: '1.8s',
          }}
        />

        <div className="scan-line pointer-events-none absolute inset-x-0 h-px bg-gradient-to-r from-transparent via-brand-400/30 to-transparent" />

        {particles.map((p) => (
          <Particle key={p.id} style={p.style} />
        ))}

        <div className="animate-slide-in-left relative z-10 shrink-0 p-8">
          <div className="premium-chip mb-4 inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-semibold text-brand-100">
            <Sparkles size={13} className="text-accent-400" />
            {t('login.platformBadge')}
          </div>
          <h1 className="text-3xl font-bold text-white drop-shadow-lg">{t('app.name')}</h1>
          <p className="mt-1 text-sm text-brand-300">{t('app.subtitle')}</p>
        </div>

        <div className="perspective-container relative z-10 flex flex-1 items-center justify-center px-6">
          <div className="relative">
            <div
              className="pointer-events-none absolute inset-0 -z-10 scale-95 rounded-3xl blur-3xl"
              style={{
                background:
                  'radial-gradient(ellipse at center, rgba(61,139,110,0.55) 0%, rgba(212,160,84,0.15) 50%, transparent 75%)',
              }}
            />
            <div
              className="pointer-events-none absolute inset-x-4 -bottom-4 h-8 rounded-full opacity-30 blur-xl"
              style={{ background: 'linear-gradient(to right, #3d8b6e, #d4a054, #3d8b6e)' }}
            />

            <Image
              src={heroImage}
              alt={t('login.platformBadge')}
              width={340}
              height={340}
              priority
              className="animate-hero-3d relative block h-auto max-h-[46vh] w-auto max-w-[340px] rounded-2xl"
              style={{
                boxShadow:
                  '0 0 0 1px rgba(61,139,110,0.2), 0 40px 80px -20px rgba(0,0,0,0.9), 0 20px 40px -10px rgba(61,139,110,0.2)',
                filter: 'brightness(1.05) contrast(1.05) saturate(1.1)',
              }}
            />
          </div>
        </div>

        <div className="animate-slide-in-left stagger-3 relative z-10 shrink-0 p-8">
          <div className="mb-3 h-px bg-gradient-to-r from-brand-500/60 via-accent-400/60 to-transparent" />
          <p className="max-w-xs text-sm leading-relaxed text-brand-300">{t('login.tagline')}</p>
          <div className="mt-3 flex items-center gap-2 text-xs text-brand-400">
            <ShieldCheck size={14} className="text-accent-400" />
            {t('login.securityNote')}
          </div>
        </div>
      </div>

      {/* ===== RIGHT PANEL ===== */}
      <div className="relative flex h-full flex-1 flex-col items-center justify-center overflow-hidden px-6 py-8">
        <div
          className="pointer-events-none absolute inset-0 opacity-[0.04]"
          style={{
            backgroundImage:
              'linear-gradient(rgba(61,139,110,1) 1px, transparent 1px), linear-gradient(90deg, rgba(61,139,110,1) 1px, transparent 1px)',
            backgroundSize: '48px 48px',
          }}
        />

        <div
          className="glow-pulse pointer-events-none absolute -right-20 top-0 h-64 w-64 rounded-full blur-3xl"
          style={{ background: 'radial-gradient(circle, rgba(61,139,110,0.12), transparent 70%)' }}
        />
        <div
          className="glow-pulse pointer-events-none absolute -bottom-16 -left-16 h-56 w-56 rounded-full blur-3xl"
          style={{
            background: 'radial-gradient(circle, rgba(212,160,84,0.1), transparent 70%)',
            animationDelay: '2s',
          }}
        />

        <div className="premium-card premium-card-glow shine-border animate-slide-in-right animate-border-glow relative z-10 w-full max-w-[400px] rounded-3xl p-8">
          <div className="pointer-events-none absolute inset-x-0 top-0 h-px rounded-t-2xl bg-gradient-to-r from-transparent via-brand-400/50 to-transparent" />

          <div className="mb-7 animate-fade-in-up">
            <div
              className="premium-chip mb-3 inline-flex h-12 w-12 items-center justify-center rounded-xl"
              style={{
                background: 'linear-gradient(145deg, #3d8b6e 0%, #255a47 100%)',
                boxShadow: '0 8px 20px -4px rgba(45,111,87,0.7)',
                color: '#fff',
              }}
            >
              <Lock size={22} />
            </div>
            <h2 className="text-2xl font-bold text-[var(--premium-text)]">{t('auth.welcome')}</h2>
            <p className="mt-1 text-sm text-[var(--premium-muted-text)]">{t('auth.subtitle')}</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="animate-fade-in-up stagger-1">
              <label className="mb-1.5 block text-xs font-medium text-[var(--premium-label)]">
                {t('auth.email')}
              </label>
              <div className="relative">
                <User
                  size={15}
                  className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-[var(--premium-label)]"
                />
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onFocus={() => setFocused('email')}
                  onBlur={() => setFocused(null)}
                  required
                  autoComplete="email"
                  className="w-full rounded-xl border py-2.5 pl-10 pr-4 text-sm focus:outline-none"
                  style={{
                    background: 'var(--premium-field-bg)',
                    color: 'var(--premium-field-text)',
                    borderColor:
                      focused === 'email' ? 'rgba(61,139,110,0.7)' : 'var(--premium-border)',
                    boxShadow:
                      focused === 'email'
                        ? '0 0 0 3px rgba(61,139,110,0.15), inset 0 1px 2px rgba(0,0,0,0.08)'
                        : 'inset 0 1px 2px rgba(0,0,0,0.08)',
                    transition: 'border-color 0.2s, box-shadow 0.2s',
                  }}
                />
              </div>
            </div>

            <div className="animate-fade-in-up stagger-2">
              <label className="mb-1.5 block text-xs font-medium text-[var(--premium-label)]">
                {t('auth.password')}
              </label>
              <div className="relative">
                <Lock
                  size={15}
                  className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-[var(--premium-label)]"
                />
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  onFocus={() => setFocused('password')}
                  onBlur={() => setFocused(null)}
                  required
                  autoComplete="current-password"
                  className="w-full rounded-xl border py-2.5 pl-10 pr-4 text-sm focus:outline-none"
                  style={{
                    background: 'var(--premium-field-bg)',
                    color: 'var(--premium-field-text)',
                    borderColor:
                      focused === 'password' ? 'rgba(61,139,110,0.7)' : 'var(--premium-border)',
                    boxShadow:
                      focused === 'password'
                        ? '0 0 0 3px rgba(61,139,110,0.15), inset 0 1px 2px rgba(0,0,0,0.08)'
                        : 'inset 0 1px 2px rgba(0,0,0,0.08)',
                    transition: 'border-color 0.2s, box-shadow 0.2s',
                  }}
                />
              </div>
            </div>

            <div className="animate-fade-in-up stagger-3 pt-2">
              <button
                type="submit"
                disabled={submitting}
                className="press-btn shine-hover relative w-full overflow-hidden rounded-xl py-3 text-sm font-semibold text-white disabled:opacity-60"
                style={{
                  background: 'linear-gradient(145deg, #3d8b6e 0%, #255a47 60%, #1f4839 100%)',
                  boxShadow:
                    '0 1px 0 rgba(255,255,255,0.12) inset, 0 8px 24px -6px rgba(45,111,87,0.65)',
                }}
              >
                <span className="animate-shimmer absolute inset-0" />
                <span className="relative">
                  {submitting ? t('common.loading') : t('auth.login')}
                </span>
              </button>
            </div>
          </form>

          <div className="mt-6 flex animate-fade-in-up stagger-4 items-center gap-3">
            <div className="h-px flex-1 bg-[var(--premium-divider)]" />
            <div className="flex items-center gap-1.5 text-xs text-[var(--premium-muted-text)]">
              <ShieldCheck size={12} className="text-accent-400/70" />
              {t('login.securedFooter')}
            </div>
            <div className="h-px flex-1 bg-[var(--premium-divider)]" />
          </div>
        </div>

        <p className="absolute bottom-5 text-xs text-[var(--premium-muted-text)] lg:hidden">
          {t('login.mobileFooter')}
        </p>
      </div>
    </div>
  )
}
