"use client"

import { useState } from "react"
import Image from "next/image"
import { Eye, EyeOff, Loader2, AlertCircle, Shield } from "lucide-react"
import { setStoredCurrentUser, clearStoredCurrentUser } from "@/lib/current-user-cache"
type Lang = "en"

const translations: Record<
  Lang,
  {
    welcome: string
    subtitle: string
    staffOnly: string
    emailLabel: string
    emailPlaceholder: string
    passwordLabel: string
    passwordPlaceholder: string
    loginBtn: string
    loggingIn: string
    forgotPassword: string
    errorMsg: string
    heroTitle: string
    heroTagline: string
    copyright: string
  }
> = {
  en: {
    welcome: "Welcome Back",
    subtitle: "Livist Medical Admin Panel",
    staffOnly: "Authorized Personnel Only",
    emailLabel: "Email Address",
    emailPlaceholder: "example@livist.com",
    passwordLabel: "Password",
    passwordPlaceholder: "••••••••",
    loginBtn: "Sign In",
    loggingIn: "Signing in...",
    forgotPassword: "Forgot password",
    errorMsg: "Invalid email or password. Please try again.",
    heroTitle: "Livist Medical",
    heroTagline: "Trusted healthcare solutions, powerful management.",
    copyright: "© 2026 Livist Medical. All rights reserved.",
  },
}

export default function LoginPage() {
  const [lang, setLang] = useState<Lang>("en")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState(false)

  const t = translations[lang]
  const isRtl = false

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(false)
    setIsLoading(true)
    const res = await fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
    })

    setIsLoading(false)

    if (!res.ok) {
    setError(true)
    return
    }

    // Make sure the cached name is refreshed after a new login.
    clearStoredCurrentUser()
    try {
      const meRes = await fetch("/api/admin/me", { cache: "no-store" })
      if (meRes.ok) {
        const data = await meRes.json().catch(() => ({}))
        if (data?.user) {
          setStoredCurrentUser(data.user)
        }
      }
    } catch {
      // Ignore failures, we still redirect.
    }

    window.location.href = "/dashboard"
  }

  return (
    <div
      className="min-h-screen flex"
      dir={isRtl ? "rtl" : "ltr"}
    >
      {/* ── Left panel: hero ── */}
      <div className="hidden lg:flex lg:w-[52%] relative flex-col overflow-hidden"
        style={{ background: "var(--brand-navy)" }}>

        {/* Background image */}
        <Image
          src="/images/login-bg.jpg"
          alt=""
          fill
          className="object-cover opacity-30"
          priority
        />

        {/* Decorative medical shapes */}
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          {/* Large cross */}
          <div className="animate-float-slow absolute top-[12%] left-[8%]">
            <MedicalCross size={72} color="#2BB673" opacity={0.18} />
          </div>
          <div className="animate-float-med absolute bottom-[18%] right-[10%]">
            <MedicalCross size={52} color="#2BB673" opacity={0.14} />
          </div>
          <div className="animate-float-slow absolute top-[55%] left-[18%]">
            <MedicalCross size={36} color="white" opacity={0.10} />
          </div>
          {/* Rings */}
          <div className="animate-pulse-ring absolute top-[30%] right-[15%] w-56 h-56 rounded-full border-2 border-white/10" />
          <div className="animate-pulse-ring absolute bottom-[30%] left-[5%] w-80 h-80 rounded-full border border-[#2BB673]/15"
            style={{ animationDelay: "2s" }} />
          <div className="animate-pulse-ring absolute top-[8%] right-[30%] w-32 h-32 rounded-full border border-white/08"
            style={{ animationDelay: "1s" }} />
          {/* Hexagons */}
          <div className="animate-float-med absolute top-[42%] right-[8%]">
            <Hexagon size={44} color="white" opacity={0.07} />
          </div>
          <div className="animate-float-slow absolute bottom-[10%] left-[30%]">
            <Hexagon size={60} color="#2BB673" opacity={0.09} />
          </div>
        </div>

        {/* Content */}
        <div className="relative z-10 flex flex-col h-full p-12">
          {/* Logo */}
          <div className="flex items-center gap-3">
            <div className="relative w-15 h-15 rounded-xl overflow-hidden  flex items-center justify-center p-1 shrink-0">
              <Image
                src="/images/logo.png"
                alt=""
                width={60}
                height={60}
                className="object-contain"
                priority
              />
            </div>
            <span className="text-white text-xl font-bold tracking-wide font-sans">
              Livist Medical
            </span>
          </div>

          {/* Hero text */}
          <div className="mt-auto mb-16">
            <p className="text-white/50 text-sm uppercase tracking-[0.2em] mb-4 font-sans">
              Health Management System
            </p>
            <h1 className="text-white font-bold leading-tight text-balance font-sans"
              style={{ fontSize: "clamp(2rem, 3.5vw, 2.75rem)" }}>
              {t.heroTitle}
            </h1>
            <p className="text-white/65 mt-4 text-lg leading-relaxed max-w-sm font-sans">
              {t.heroTagline}
            </p>

            {/* Feature badges */}
            <div className="flex flex-wrap gap-3 mt-8">
              {["Secure Access", "GDPR Compliant", "24/7 Support"].map((badge) => (
                <span
                  key={badge}
                  className="px-3 py-1.5 rounded-full text-xs font-medium font-sans text-white/80"
                  style={{ background: "rgba(255,255,255,0.10)", border: "1px solid rgba(255,255,255,0.15)" }}
                >
                  {badge}
                </span>
              ))}
            </div>
          </div>

          <p className="text-white/30 text-xs font-sans">{t.copyright}</p>
        </div>
      </div>

      {/* ── Right panel: form ── */}
      <div className="flex-1 flex flex-col bg-background">
        {/* Top bar */}
        <div className="flex items-center justify-between px-8 py-5 border-b border-border md:hidden">
          {/* Mobile logo */}
          <div className="flex items-center gap-2 lg:hidden">
            <div className="relative w-8 h-8 rounded-lg overflow-hidden bg-white/10 flex items-center justify-center p-0.5 shrink-0">
              <Image
                src="/images/logo.png"
                alt=""
                width={32}
                height={32}
                className="object-contain"
              />
            </div>
            <span className="font-bold text-foreground font-sans text-sm">Livist Medical</span>
          </div>

        </div>

        {/* Form area */}
        <div className="flex-1 flex items-center justify-center p-8">
          <div className="w-full max-w-[420px]">
            {/* Staff Only badge */}
            <div className="flex items-center gap-2 mb-8">
              <Shield className="w-4 h-4" style={{ color: "var(--brand-green)" }} />
              <span
                className="text-xs font-semibold uppercase tracking-widest px-3 py-1 rounded-full font-sans"
                style={{
                  background: "rgba(43,182,115,0.10)",
                  color: "var(--brand-green)",
                  border: "1px solid rgba(43,182,115,0.25)",
                }}
              >
                {t.staffOnly}
              </span>
            </div>

            <h2 className="text-3xl font-bold text-foreground text-balance font-sans">{t.welcome}</h2>
            <p className="mt-1.5 text-muted-foreground text-sm font-sans">{t.subtitle}</p>

            <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-5">
              {/* Email */}
              <div className="flex flex-col gap-1.5">
                <label className="text-sm font-semibold text-foreground font-sans" htmlFor="email">
                  {t.emailLabel}
                </label>
                <input
                  id="email"
                  type="email"
                  autoComplete="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder={t.emailPlaceholder}
                  disabled={isLoading}
                  className="w-full px-4 py-3 rounded-xl border border-border bg-card text-foreground placeholder:text-muted-foreground text-sm font-sans transition-all outline-none focus:border-[var(--brand-green)] focus:ring-2 focus:ring-[var(--brand-green)]/20 disabled:opacity-60"
                />
              </div>

              {/* Password */}
              <div className="flex flex-col gap-1.5">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-semibold text-foreground font-sans" htmlFor="password">
                    {t.passwordLabel}
                  </label>
                  <button
                    type="button"
                    className="text-xs font-sans transition-colors"
                    style={{ color: "var(--brand-green)" }}
                  >
                    {t.forgotPassword}
                  </button>
                </div>
                <div className="relative">
                  <input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    autoComplete="current-password"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder={t.passwordPlaceholder}
                    disabled={isLoading}
                    className="w-full px-4 py-3 pr-11 rounded-xl border border-border bg-card text-foreground placeholder:text-muted-foreground text-sm font-sans transition-all outline-none focus:border-[var(--brand-green)] focus:ring-2 focus:ring-[var(--brand-green)]/20 disabled:opacity-60"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    aria-label={showPassword ? "Hide password" : "Show password"}
                    className="absolute cursor-pointer right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {/* Error */}
              {error && (
                <div
                  className="flex items-center gap-2.5 px-4 py-3 rounded-xl text-sm font-sans"
                  style={{
                    background: "rgba(239,68,68,0.08)",
                    border: "1px solid rgba(239,68,68,0.2)",
                    color: "#dc2626",
                  }}
                  role="alert"
                >
                  <AlertCircle className="w-4 h-4 shrink-0" />
                  <span>{t.errorMsg}</span>
                </div>
              )}

              {/* Submit */}
              <button
                type="submit"
                disabled={isLoading}
                className="w-full cursor-pointer py-3.5 rounded-xl text-white font-semibold text-sm font-sans transition-all duration-200 flex items-center justify-center gap-2 mt-1 disabled:opacity-70 disabled:cursor-not-allowed hover:brightness-105 active:scale-[0.99]"
                style={{ background: "var(--brand-green)" }}
              >
                {isLoading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {t.loggingIn}
                  </>
                ) : (
                  t.loginBtn
                )}
              </button>
            </form>

          </div>
        </div>

        {/* Bottom */}
        <div className="px-8 py-4 text-center text-xs text-muted-foreground font-sans border-t border-border">
          {t.copyright}
        </div>
      </div>
    </div>
  )
}

/* ─── Inline SVG helpers ─── */
function MedicalCross({ size, color, opacity }: { size: number; color: string; opacity: number }) {
  const arm = size * 0.3
  const core = size * 0.4
  return (
    <svg width={size} height={size} viewBox="0 0 30 30" fill="none" aria-hidden="true">
      <rect x={(30 - arm * 30 / size) / 2} y="0" width={arm * 30 / size} height={30}
        rx="3" fill={color} fillOpacity={opacity} />
      <rect x="0" y={(30 - arm * 30 / size) / 2} width={30} height={arm * 30 / size}
        rx="3" fill={color} fillOpacity={opacity} />
    </svg>
  )
}

function Hexagon({ size, color, opacity }: { size: number; color: string; opacity: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 60 60" fill="none" aria-hidden="true">
      <polygon
        points="30,2 55,16 55,44 30,58 5,44 5,16"
        stroke={color}
        strokeOpacity={opacity}
        strokeWidth="2"
        fill="none"
      />
    </svg>
  )
}
