"use client";

import { useMutation } from "@tanstack/react-query";
import { ShieldCheck } from "lucide-react";
import { CSSProperties, FormEvent, useState } from "react";
import { api } from "@/lib/api";
import type { LoginResponse } from "@/lib/types";
import { createTranslator, DEFAULT_LOCALE } from "@/lib/i18n";
import { isLoginThemeName, loginThemes } from "@/lib/login-theme";
import { useRuntimeBranding } from "@/lib/runtime-branding";
import { BrandLogo } from "./brand-logo";

type LoginScreenProps = {
  onSignedIn: (data?: LoginResponse) => void;
  brandDomain?: string;
};

export function LoginScreen({ onSignedIn, brandDomain = "" }: LoginScreenProps) {
  return <LoginScreenInner onSignedIn={onSignedIn} brandDomain={brandDomain} />;
}

function LoginScreenInner({ onSignedIn, brandDomain = "" }: LoginScreenProps) {
  const branding = useRuntimeBranding(brandDomain);
  const [form, setForm] = useState({ email: "", password: "" });
  const [twoFactorChallenge, setTwoFactorChallenge] = useState<{ token: string; expiresIn: number } | null>(null);
  const [twoFactorCode, setTwoFactorCode] = useState("");
  const t = createTranslator(DEFAULT_LOCALE);
  const loginTheme = loginThemes[isLoginThemeName(branding.loginTheme) ? branding.loginTheme : "mint"];
  const loginIllustrationUrl = branding.loginLandscapeOnly ? loginTheme.landscapeIllustrationUrl : loginTheme.illustrationUrl;
  const isPastelLoginTheme = loginTheme.mood === "pastel";
  const customLogin = branding.loginDesignMode === "custom";
  const template = branding.loginTemplate;
  const formOrder = template === "panel-right" ? "md:order-2 md:justify-self-end" : template === "centered" ? "md:col-span-2 md:justify-self-center" : "md:order-1 md:justify-self-start";
  const heroOrder = template === "panel-right" ? "md:order-1" : template === "centered" ? "md:hidden" : "md:order-2";

  const login = useMutation({
    mutationFn: api.login,
    onSuccess: (data) => {
      if (data.two_factor_required && data.challenge_token) {
        setTwoFactorChallenge({ token: data.challenge_token, expiresIn: data.challenge_expires_in });
        setTwoFactorCode("");
        return;
      }
      setTwoFactorChallenge(null);
      onSignedIn(data);
    },
  });

  const verifyTwoFactor = useMutation({
    mutationFn: api.loginTwoFactor,
    onSuccess: (data) => {
      setTwoFactorChallenge(null);
      setTwoFactorCode("");
      onSignedIn(data);
    },
  });

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (twoFactorChallenge) {
      verifyTwoFactor.mutate({ challenge_token: twoFactorChallenge.token, code: twoFactorCode });
      return;
    }
    login.mutate(form);
  }

  if (!branding.ready) {
    return <LoginThemeLoadingShell />;
  }

  return (
    <main
      className="relative min-h-[100dvh] overflow-x-hidden px-3 py-3 sm:px-5 sm:py-5 md:grid md:place-items-center md:px-6 md:py-6 lg:px-8 lg:py-7"
      style={{
        "--accent": loginTheme.accent,
        "--login-canvas": customLogin ? branding.loginBackgroundColor : loginTheme.canvas,
        "--login-panel": customLogin ? branding.loginGradientColor : loginTheme.panel,
        "--login-heading": loginTheme.heading,
        "--login-body": loginTheme.body,
        "--login-supporting": loginTheme.supporting,
        "--login-brand-name": branding.loginBrandNameColor || loginTheme.heading,
        "--login-tagline": branding.loginTaglineColor || loginTheme.body,
        "--login-supporting-text": branding.loginSupportingTextColor || loginTheme.supporting,
      } as CSSProperties}
    >
      <div
        className="pointer-events-none absolute inset-0"
        style={{
          background: customLogin
            ? `linear-gradient(135deg, ${branding.loginBackgroundColor} 0%, ${branding.loginGradientColor} 100%)`
            : isPastelLoginTheme
            ? "radial-gradient(circle at 18% 12%, color-mix(in srgb, var(--login-panel) 58%, white) 0%, transparent 34rem), radial-gradient(circle at 84% 18%, color-mix(in srgb, var(--login-canvas) 62%, white) 0%, transparent 30rem), linear-gradient(135deg, color-mix(in srgb, var(--login-canvas) 78%, white) 0%, var(--login-canvas) 42%, color-mix(in srgb, var(--login-panel) 74%, white) 100%)"
            : "linear-gradient(135deg, color-mix(in srgb, var(--login-canvas) 54%, black) 0%, var(--login-canvas) 36%, color-mix(in srgb, var(--login-panel) 46%, var(--login-canvas)) 72%, color-mix(in srgb, var(--login-canvas) 58%, black) 100%)",
        }}
      />

      <section
        className="relative mx-auto w-full max-w-[1080px] overflow-hidden rounded-xl bg-[var(--login-panel)] md:min-h-[min(570px,calc(100dvh-2.5rem))] lg:min-h-[min(634px,calc(100dvh-3.5rem))]"
        style={{
          boxShadow: isPastelLoginTheme
            ? "0 24px 80px color-mix(in srgb, var(--login-heading) 18%, transparent), 0 0 0 1px color-mix(in srgb, var(--login-heading) 10%, white)"
            : "18px 18px 0 color-mix(in srgb, var(--login-canvas) 80%, black)",
        }}
      >
        <div
          aria-hidden="true"
          className="absolute inset-0 bg-cover bg-[center_bottom] bg-no-repeat"
          style={{
            backgroundImage: `url('${customLogin && branding.loginBackgroundUrl ? branding.loginBackgroundUrl : loginIllustrationUrl}')`,
            backgroundPosition: customLogin ? (template === "panel-left" || template === "split" ? "right center" : template === "panel-right" ? "left center" : "center") : "center",
            backgroundSize: customLogin && branding.loginBackgroundUrl ? (template === "split" ? "50% 100%" : "cover") : "contain",
            backgroundRepeat: "no-repeat",
            filter: isPastelLoginTheme ? "brightness(1.04) saturate(1.04)" : undefined,
            opacity: 1,
          }}
        />
        {isPastelLoginTheme ? (
          <div
            aria-hidden="true"
            className="absolute inset-0"
            style={{
              background:
                "linear-gradient(90deg, color-mix(in srgb, var(--login-panel) 10%, transparent) 0%, color-mix(in srgb, white 14%, transparent) 46%, color-mix(in srgb, var(--login-canvas) 18%, transparent) 100%)",
            }}
          />
        ) : null}
        <div className={`relative z-10 grid content-start gap-5 px-5 py-7 sm:px-10 sm:py-8 md:min-h-[min(570px,calc(100dvh-2.5rem))] md:content-normal md:items-center md:gap-6 md:px-8 md:py-8 lg:min-h-[min(634px,calc(100dvh-3.5rem))] lg:gap-[78px] lg:px-16 lg:py-12 ${template === "centered" && customLogin ? "md:grid-cols-2" : "md:grid-cols-[284px_minmax(0,1fr)] lg:grid-cols-[318px_minmax(0,1fr)]"}`}>
          <form onSubmit={submit} style={customLogin ? { backgroundColor: `rgba(255,255,255,${(100 - branding.loginBoxTransparency) / 100})` } : undefined} className={`order-2 grid w-full max-w-[318px] justify-self-center gap-4 rounded-[42px] px-7 py-6 shadow-[0_12px_26px_rgba(2,59,71,0.20)] backdrop-blur-sm sm:px-8 sm:py-7 md:max-w-[284px] md:gap-3 md:rounded-[34px] md:px-6 md:py-6 lg:max-w-[318px] lg:gap-5 lg:rounded-[42px] lg:px-8 lg:py-8 ${customLogin ? formOrder : "bg-white/95 md:order-1 md:justify-self-start md:bg-white"}`}>
            <div className="grid justify-items-center gap-3 text-center">
              <div className="grid h-[88px] w-[88px] place-items-center rounded-full bg-[#f1f8f9] p-3 sm:h-[96px] sm:w-[96px] md:h-[84px] md:w-[84px] lg:h-[112px] lg:w-[112px] lg:p-4">
                <BrandLogo size="lg" centered brandDomain={brandDomain} className="[&>div:first-child]:!h-full [&>div:first-child]:!w-full" />
              </div>
              <div className="grid gap-1">
                <h2 className="text-xl font-black leading-tight text-slate-950">{t("login.signIn")}</h2>
                <p className="text-xs leading-5 text-slate-600">{t("login.help")}</p>
              </div>
            </div>

            <div className="grid gap-3">
              <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
                {t("login.email")}
                <input
                  autoFocus
                  className="field h-11 px-3"
                  type="email"
                  value={form.email}
                  onChange={(event) => setForm({ ...form, email: event.target.value })}
                  placeholder="you@company.com"
                  required
                />
              </label>

              <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
                {t("login.password")}
                <input
                  className="field h-11 px-3"
                  type="password"
                  value={form.password}
                  onChange={(event) => setForm({ ...form, password: event.target.value })}
                  placeholder={t("login.passwordPlaceholder")}
                  required
                />
              </label>
            </div>

            {twoFactorChallenge ? (
              <div className="grid gap-3 rounded-lg border border-slate-200 bg-slate-50 p-4">
                <div className="flex items-start gap-3">
                  <div className="mt-0.5 rounded-full bg-white p-2 text-emerald-700 shadow-sm">
                    <ShieldCheck size={16} />
                  </div>
                  <div>
                    <strong className="block text-sm font-black text-slate-900">{t("login.twoFactorCode")}</strong>
                    <p className="mt-1 text-sm leading-6 text-slate-600">{t("login.twoFactorHelp")}</p>
                  </div>
                </div>
                <label className="grid gap-2 text-sm font-semibold text-slate-700">
                  {t("login.code")}
                  <input
                    autoFocus
                    className="field h-11 px-3 tracking-[0.24em]"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    value={twoFactorCode}
                    onChange={(event) => setTwoFactorCode(event.target.value.replace(/\D/g, "").slice(0, 10))}
                    placeholder="123456"
                    required
                  />
                </label>
              </div>
            ) : null}

            {login.error ? <p className="rounded-lg border border-rose-100 bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">{login.error.message}</p> : null}
            {verifyTwoFactor.error ? <p className="rounded-lg border border-rose-100 bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">{verifyTwoFactor.error.message}</p> : null}

            <div className="grid gap-3">
              <button className="theme-button h-11 w-full" disabled={login.isPending || verifyTwoFactor.isPending}>
                {twoFactorChallenge ? (verifyTwoFactor.isPending ? t("login.verifying") : t("login.signIn")) : login.isPending ? t("login.signingIn") : t("login.signIn")}
              </button>
              {twoFactorChallenge ? (
                <button
                  type="button"
                  onClick={() => {
                    setTwoFactorChallenge(null);
                    setTwoFactorCode("");
                  }}
                  className="theme-button-soft h-11 w-full"
                >
                  {t("login.back")}
                </button>
              ) : null}
            </div>
          </form>

          <aside className={`order-1 grid content-start gap-3 md:self-start md:gap-4 md:pt-6 ${customLogin ? heroOrder : "md:order-2"}`}>
            <div className="mx-auto w-full max-w-[475px] text-center md:mx-0 md:text-left">
              <h1 className="text-balance text-3xl font-black leading-[1.04] tracking-[-0.02em] text-[var(--login-brand-name)] sm:text-4xl md:text-3xl lg:text-4xl xl:whitespace-nowrap xl:text-[2.65rem]">
                {branding.name}
              </h1>
              <p className="mt-3 max-w-[39rem] text-sm font-medium leading-6 text-[var(--login-tagline)] sm:text-base lg:mt-4">
                {branding.tagline}
              </p>
              <p className="mt-2 max-w-[36rem] text-sm leading-5 text-[var(--login-supporting-text)] md:hidden lg:block">
                {t("login.heroCopy")}
              </p>
              <div className="mx-auto mt-3 inline-flex w-fit items-center gap-2 rounded-full bg-white px-3.5 py-2 text-xs font-black text-[var(--accent)] shadow-[0_3px_10px_rgba(0,0,0,0.14)] md:mx-0">
                <span className="h-2 w-2 rounded-full bg-[var(--accent)]" />
                {t("login.workspaceBadge")}
              </div>
            </div>
          </aside>
        </div>
      </section>
    </main>
  );
}

function LoginThemeLoadingShell() {
  return <main className="min-h-[100dvh] bg-[#f7f9fc]" />;
}
