"use client"

import type React from "react"
import { useEffect, useRef, useState } from "react"
import { useRouter } from "next/navigation"
import {
  Mail,
  Lock,
  KeyRound,
  ArrowLeft,
  CheckCircle2,
  Eye,
  EyeOff,
  Flag,
} from "lucide-react"
import { TwoFactorSetupForm, TwoFactorVerifyForm } from "@/components/two-factor-flow"

// Locked "Forest Green" palette (V0-redesign 2026-08-01, basert på Stitch --
// se DESIGN_SYSTEM.md sitt notat om denne runden). Anvendt inline med vilje,
// slik at ingenting tolkes om ved en senere V0-reeksport.
const C = {
  card: "rgba(255, 255, 255, 0.72)",
  ink: "#012c11", // primærtekst + primærknapp-bakgrunn
  inkOn: "#ffffff",
  accent: "#1a4325", // mørkegrønne aksenter (header-gradient)
  accentMuted: "#bfeec4", // dempet tekst PÅ mørkegrønn -- ALDRI #84b089/#a4a5a5 her (målt ~4.5:1, under vårt AAA-mål)
  successBg: "#91f78e",
  successInk: "#00731e",
  muted: "#424941", // dempet brødtekst på hvit bakgrunn
  border: "#c1c9bf",
  fieldBg: "#ffffff",
} as const

const RESEND_COOLDOWN = 30 // seconds

type SessionUser = {
  id: string
  email: string
  display_name: string
  preferred_locale: string
}

type LoginResult = {
  status: "success" | "2fa_required" | "2fa_setup_required"
  user?: SessionUser
  two_factor_method?: "totp" | "email"
}

// ADR-021 Beslutning E: primær-autentisering (magic-link ELLER passord) kan
// returnere tre ulike utfall -- delt mellom denne komponenten og
// verify-form.tsx sin håndtering av magic-link-svaret.
type PostAuthMode = "2fa-verify" | "2fa-setup" | null

type Mode = "default" | "sent" | "password" | "join" | "verify"

function isValidEmail(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())
}

export function LoginForm() {
  const router = useRouter()
  const [mode, setMode] = useState<Mode>("default")
  const [postAuth, setPostAuth] = useState<PostAuthMode>(null)
  const [twoFactorMethod, setTwoFactorMethod] = useState<"totp" | "email" | null>(null)
  const [email, setEmail] = useState("")
  const [emailTouched, setEmailTouched] = useState(false)
  const [sending, setSending] = useState(false)
  const [cooldown, setCooldown] = useState(0)
  const [error, setError] = useState<string | null>(null)

  const emailValid = isValidEmail(email)
  const emailError = emailTouched && email.length > 0 && !emailValid

  function handleLoginResult(result: LoginResult) {
    if (result.status === "success") {
      router.replace("/dashboard")
    } else if (result.status === "2fa_required") {
      setTwoFactorMethod(result.two_factor_method ?? "totp")
      setPostAuth("2fa-verify")
    } else {
      setPostAuth("2fa-setup")
    }
  }

  function handleTwoFactorSuccess() {
    router.replace("/dashboard")
  }

  // Countdown timer for the resend cooldown.
  useEffect(() => {
    if (cooldown <= 0) return
    const id = setInterval(() => setCooldown((c) => (c <= 1 ? 0 : c - 1)), 1000)
    return () => clearInterval(id)
  }, [cooldown])

  async function sendLink() {
    setSending(true)
    setError(null)
    try {
      // Alltid samme suksess-respons uansett om e-posten finnes (anti-
      // enumerering, se ADR-009) -- kun nettverks-/serverfeil havner i catch.
      const res = await fetch("/auth/request-link", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ email: email.trim(), locale: "nb" }),
      })
      if (!res.ok) throw new Error(`request-link: ${res.status}`)
      setMode("sent")
      setCooldown(RESEND_COOLDOWN)
    } catch {
      setError("Klarte ikke å sende lenken. Sjekk tilkoblingen og prøv igjen.")
    } finally {
      setSending(false)
    }
  }

  function submitDefault(e: React.FormEvent) {
    e.preventDefault()
    setEmailTouched(true)
    if (!emailValid || sending) return
    void sendLink()
  }

  function resend() {
    if (cooldown > 0 || sending) return
    void sendLink()
  }

  function backToDefault() {
    setMode("default")
    setEmailTouched(false)
    setError(null)
  }

  return (
    <div className="relative w-full">
      {/* Soft green glow behind the card so the glass blur has something to work against */}
      <div aria-hidden="true" className="pointer-events-none absolute inset-0 -z-10 overflow-visible">
        <div
          className="absolute -left-10 -top-12 size-40 rounded-full blur-3xl"
          style={{ backgroundColor: "rgba(26, 67, 37, 0.18)" }}
        />
        <div
          className="absolute -bottom-14 -right-8 size-44 rounded-full blur-3xl"
          style={{ backgroundColor: "rgba(145, 247, 142, 0.28)" }}
        />
      </div>

      <div
        className="w-full overflow-hidden rounded-3xl border backdrop-blur-xl"
        style={{
          backgroundColor: C.card,
          borderColor: C.border,
          boxShadow: "0 24px 60px -24px rgba(1, 44, 17, 0.45), 0 8px 20px -12px rgba(1, 44, 17, 0.2)",
        }}
      >
        {/* 2FA bruker de EKSISTERENDE, sikkerhetskritiske komponentene uendret
            (egen intern overskrift) -- kun logo-raden fra det nye headeret
            vises over dem, ikke tittel/undertekst-blokken, for å unngå
            dobbel overskrift. */}
        <CardHeader mode={mode} showTitle={postAuth === null} />

        <div className="flex flex-col gap-6 p-6 sm:p-7">
          {postAuth === "2fa-verify" ? (
            <TwoFactorVerifyForm
              method={twoFactorMethod ?? "totp"}
              onSuccess={handleTwoFactorSuccess}
              onBack={() => setPostAuth(null)}
            />
          ) : postAuth === "2fa-setup" ? (
            <TwoFactorSetupForm forced onSuccess={handleTwoFactorSuccess} />
          ) : mode === "default" ? (
            <DefaultState
              email={email}
              setEmail={setEmail}
              emailError={emailError}
              onBlur={() => setEmailTouched(true)}
              onSubmit={submitDefault}
              sending={sending}
              error={error}
              onPassword={() => setMode("password")}
              onJoin={() => setMode("join")}
            />
          ) : mode === "sent" ? (
            <SentState
              email={email}
              cooldown={cooldown}
              sending={sending}
              error={error}
              onResend={resend}
              onBack={backToDefault}
            />
          ) : mode === "password" ? (
            <PasswordState onResult={handleLoginResult} onBack={() => setMode("default")} />
          ) : (
            <JoinState onBack={() => setMode("default")} />
          )}
        </div>
      </div>
    </div>
  )
}

/* --- Shared shell -------------------------------------------------------- */

const HEADINGS: Record<Mode, { title: string; subtitle: string }> = {
  default: {
    title: "Velkommen til TeeCup",
    subtitle: "Logg inn for å følge turneringen din live.",
  },
  sent: {
    title: "Sjekk innboksen din",
    subtitle: "Vi har sendt deg en sikker innloggingslenke.",
  },
  password: {
    title: "Logg inn med passord",
    subtitle: "Skriv inn e-post og passord for å fortsette.",
  },
  join: {
    title: "Gå rett til turneringen",
    subtitle: "Har du fått en invitasjonskode? Skriv den inn her.",
  },
  verify: {
    title: "Bekreft innloggingen",
    subtitle: "Vi har sendt en kode for å bekrefte at det er deg.",
  },
}

function CardHeader({ mode, showTitle }: { mode: Mode; showTitle: boolean }) {
  const { title, subtitle } = HEADINGS[mode]
  return (
    <div
      className="flex flex-col items-center gap-3 px-6 pt-8 pb-6 text-center"
      style={{
        background: `linear-gradient(180deg, ${C.accent} 0%, #123019 100%)`,
      }}
    >
      <div className="flex items-center gap-2.5">
        <div
          className="flex size-11 items-center justify-center rounded-2xl"
          style={{ backgroundColor: "rgba(255,255,255,0.12)" }}
        >
          <Flag aria-hidden="true" className="size-6 text-brand-orange" fill="currentColor" />
        </div>
        <span className="text-2xl font-extrabold tracking-tight" style={{ color: C.inkOn }}>
          TeeCup
        </span>
      </div>
      {showTitle && (
        <div className="flex flex-col gap-1">
          <h1 className="text-xl font-bold tracking-tight text-balance" style={{ color: C.inkOn }}>
            {title}
          </h1>
          <p className="text-sm leading-relaxed text-pretty" style={{ color: C.accentMuted }}>
            {subtitle}
          </p>
        </div>
      )}
    </div>
  )
}

/* --- Reusable field + button -------------------------------------------- */

function FieldLabel({ htmlFor, children }: { htmlFor: string; children: React.ReactNode }) {
  return (
    <label htmlFor={htmlFor} className="text-sm font-semibold" style={{ color: C.ink }}>
      {children}
    </label>
  )
}

function TextInput({
  id,
  icon: Icon,
  invalid,
  trailing,
  ...props
}: React.InputHTMLAttributes<HTMLInputElement> & {
  id: string
  icon: typeof Mail
  invalid?: boolean
  trailing?: React.ReactNode
}) {
  return (
    <div className="relative">
      <Icon
        aria-hidden="true"
        className="pointer-events-none absolute left-4 top-1/2 size-5 -translate-y-1/2"
        style={{ color: C.muted }}
      />
      <input
        id={id}
        name={id}
        className="h-14 w-full rounded-2xl border pl-12 pr-4 text-base font-medium outline-none transition-shadow placeholder:font-normal focus-visible:ring-2 focus-visible:ring-[#1a4325] focus-visible:ring-offset-1"
        style={{
          backgroundColor: C.fieldBg,
          borderColor: invalid ? "#b3261e" : C.border,
          color: C.ink,
        }}
        {...props}
      />
      {trailing}
    </div>
  )
}

function PrimaryButton({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) {
  return (
    <button
      className="flex h-14 w-full items-center justify-center rounded-2xl text-base font-bold transition-opacity disabled:opacity-60"
      style={{ backgroundColor: C.ink, color: C.inkOn }}
      {...props}
    >
      {children}
    </button>
  )
}

function BackLink({ children, onClick }: { children: React.ReactNode; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="inline-flex min-h-12 items-center justify-center gap-1.5 rounded-xl px-3 text-sm font-semibold transition-colors hover:underline"
      style={{ color: C.accent }}
    >
      <ArrowLeft aria-hidden="true" className="size-4" />
      {children}
    </button>
  )
}

function SecondaryLink({
  icon: Icon,
  children,
  onClick,
}: {
  icon: typeof Lock
  children: React.ReactNode
  onClick: () => void
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="inline-flex min-h-12 items-center gap-2.5 rounded-xl px-2 text-left text-sm font-semibold transition-colors hover:underline"
      style={{ color: C.accent }}
    >
      <Icon aria-hidden="true" className="size-4 shrink-0" />
      {children}
    </button>
  )
}

/* --- State 1: Default (magic link), ekte /auth/request-link -------------- */

function DefaultState({
  email,
  setEmail,
  emailError,
  onBlur,
  onSubmit,
  sending,
  error,
  onPassword,
  onJoin,
}: {
  email: string
  setEmail: (v: string) => void
  emailError: boolean
  onBlur: () => void
  onSubmit: (e: React.FormEvent) => void
  sending: boolean
  error: string | null
  onPassword: () => void
  onJoin: () => void
}) {
  return (
    <form onSubmit={onSubmit} className="flex flex-col gap-6" noValidate>
      <div className="flex flex-col gap-2">
        <FieldLabel htmlFor="email">E-post</FieldLabel>
        <TextInput
          id="email"
          icon={Mail}
          type="email"
          inputMode="email"
          autoComplete="email"
          autoFocus
          placeholder="deg@epost.no"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          onBlur={onBlur}
          invalid={emailError}
          aria-invalid={emailError}
          aria-describedby={emailError ? "email-error" : undefined}
        />
        {emailError && (
          <p id="email-error" className="text-sm font-medium" style={{ color: "#b3261e" }}>
            Skriv inn en gyldig e-postadresse.
          </p>
        )}
      </div>

      {error && (
        <p role="alert" className="text-center text-sm font-medium" style={{ color: "#b3261e" }}>
          {error}
        </p>
      )}

      <PrimaryButton type="submit" disabled={sending}>
        {sending ? "Sender …" : "Send innloggingslenke"}
      </PrimaryButton>

      <p className="text-center text-sm leading-relaxed text-pretty" style={{ color: C.muted }}>
        Ingen passord nødvendig. Vi sender deg en sikker lenke på e-post.
      </p>

      <div className="flex flex-col gap-1 border-t pt-4" style={{ borderColor: C.border }}>
        <SecondaryLink icon={Lock} onClick={onPassword}>
          Logg inn med e-post og passord i stedet
        </SecondaryLink>
        <SecondaryLink icon={KeyRound} onClick={onJoin}>
          Har du en invitasjonskode? Gå rett til turneringen
        </SecondaryLink>
      </div>
    </form>
  )
}

/* --- State 2: Link sent, ekte resend/cooldown ----------------------------- */

function SentState({
  email,
  cooldown,
  sending,
  error,
  onResend,
  onBack,
}: {
  email: string
  cooldown: number
  sending: boolean
  error: string | null
  onResend: () => void
  onBack: () => void
}) {
  const liveRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    liveRef.current?.focus()
  }, [])

  return (
    <div className="flex flex-col items-center gap-5 text-center">
      <div
        ref={liveRef}
        tabIndex={-1}
        className="flex size-16 items-center justify-center rounded-2xl outline-none"
        style={{ backgroundColor: C.successBg }}
      >
        <CheckCircle2 aria-hidden="true" className="size-9" style={{ color: C.successInk }} />
      </div>

      <div className="w-full rounded-2xl px-4 py-3" style={{ backgroundColor: C.successBg }} aria-live="polite">
        <p className="text-sm font-semibold leading-relaxed" style={{ color: C.successInk }}>
          Lenke sendt til <span className="font-extrabold">{email || "din e-post"}</span>
        </p>
      </div>

      <p className="text-sm leading-relaxed text-pretty" style={{ color: C.muted }}>
        Åpne lenken på denne enheten for å logge inn. Det kan ta et minutt før den kommer frem.
      </p>

      {error && (
        <p role="alert" className="text-sm font-medium" style={{ color: "#b3261e" }}>
          {error}
        </p>
      )}

      <div className="w-full">
        {cooldown > 0 ? (
          <p className="text-sm" style={{ color: C.muted }} aria-live="polite">
            Fikk du ingen e-post? Send igjen om{" "}
            <span className="font-bold tabular-nums" style={{ color: C.ink }}>
              {cooldown}s
            </span>
          </p>
        ) : (
          <button
            type="button"
            onClick={onResend}
            disabled={sending}
            className="inline-flex min-h-12 items-center justify-center rounded-xl px-4 text-sm font-bold transition-opacity hover:underline disabled:opacity-60"
            style={{ color: C.ink }}
          >
            {sending ? "Sender …" : "Send lenken igjen"}
          </button>
        )}
      </div>

      <div className="w-full border-t pt-4" style={{ borderColor: C.border }}>
        <BackLink onClick={onBack}>Bruk en annen e-postadresse</BackLink>
      </div>
    </div>
  )
}

/* --- State 3: Password, ekte /auth/login-password ------------------------ */

function PasswordState({
  onResult,
  onBack,
}: {
  onResult: (result: LoginResult) => void
  onBack: () => void
}) {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!email.trim() || !password || submitting) return
    setSubmitting(true)
    setError(null)
    try {
      const res = await fetch("/auth/login-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ email: email.trim(), password }),
      })
      if (!res.ok) {
        const body = await res.json().catch(() => null)
        throw new Error(body?.detail?.message ?? "E-post eller passord er feil.")
      }
      onResult(await res.json())
    } catch (err) {
      setError(err instanceof Error ? err.message : "Noe gikk galt. Prøv igjen.")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-6" noValidate>
      <div className="flex flex-col gap-2">
        <FieldLabel htmlFor="pw-email">E-post</FieldLabel>
        <TextInput
          id="pw-email"
          icon={Mail}
          type="email"
          inputMode="email"
          autoComplete="email"
          autoFocus
          placeholder="deg@epost.no"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </div>

      <div className="flex flex-col gap-2">
        <FieldLabel htmlFor="pw-pass">Passord</FieldLabel>
        {/* Bevisst ingen begrensning på tegn -- spesialtegn/mellomrom skal fungere. */}
        <TextInput
          id="pw-pass"
          icon={Lock}
          type={showPassword ? "text" : "password"}
          autoComplete="current-password"
          placeholder="Passordet ditt"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          trailing={
            <button
              type="button"
              onClick={() => setShowPassword((v) => !v)}
              aria-label={showPassword ? "Skjul passord" : "Vis passord"}
              className="absolute right-2 top-1/2 flex size-11 -translate-y-1/2 items-center justify-center rounded-xl transition-colors"
              style={{ color: C.muted }}
            >
              {showPassword ? <EyeOff aria-hidden="true" className="size-5" /> : <Eye aria-hidden="true" className="size-5" />}
            </button>
          }
        />
      </div>

      {error && (
        <p role="alert" className="text-center text-sm font-medium" style={{ color: "#b3261e" }}>
          {error}
        </p>
      )}

      <PrimaryButton type="submit" disabled={submitting || !email.trim() || !password}>
        {submitting ? "Logger inn …" : "Logg inn"}
      </PrimaryButton>

      <div className="border-t pt-4" style={{ borderColor: C.border }}>
        <BackLink onClick={onBack}>Bruk innloggingslenke på e-post i stedet</BackLink>
      </div>
    </form>
  )
}

/* --- State 4: Join by code, ekte /public/tournaments/by-code -------------- */

function JoinState({ onBack }: { onBack: () => void }) {
  const router = useRouter()
  const [code, setCode] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    const trimmed = code.trim()
    if (!trimmed || loading) return
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`/public/tournaments/by-code/${encodeURIComponent(trimmed)}`)
      if (!res.ok) {
        const body = await res.json().catch(() => null)
        setError(body?.detail?.message ?? "Fant ingen turnering med denne koden.")
        return
      }
      const data: { tournament_id: string } = await res.json()
      router.push(`/t/${data.tournament_id}?code=${encodeURIComponent(trimmed)}`)
    } catch {
      setError("Klarte ikke å slå opp koden. Sjekk tilkoblingen og prøv igjen.")
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-6" noValidate>
      <div className="flex flex-col gap-2">
        <FieldLabel htmlFor="invite-code">Invitasjonskode</FieldLabel>
        <TextInput
          id="invite-code"
          icon={KeyRound}
          type="text"
          inputMode="text"
          autoCapitalize="characters"
          autoComplete="off"
          autoFocus
          placeholder="F.eks. RAPWAR"
          value={code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          style={{ letterSpacing: "0.08em" }}
        />
        <p className="text-sm leading-relaxed" style={{ color: C.muted }}>
          Fått en kode muntlig eller på en lapp? Skriv den inn her — du trenger ikke logge inn for å
          se turneringen eller melde deg på.
        </p>
      </div>

      {error && (
        <p role="alert" className="text-center text-sm font-medium" style={{ color: "#b3261e" }}>
          {error}
        </p>
      )}

      <PrimaryButton type="submit" disabled={loading || !code.trim()}>
        {loading ? "Sjekker …" : "Gå til turnering"}
      </PrimaryButton>

      <div className="border-t pt-4" style={{ borderColor: C.border }}>
        <BackLink onClick={onBack}>Tilbake til innlogging</BackLink>
      </div>
    </form>
  )
}
