"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import type { DemoAppConfig } from "@/lib/types";

type LoginShellProps = {
  appConfig: DemoAppConfig;
  initialError?: string | null;
  nextPath?: string;
};

export function LoginShell({
  appConfig,
  initialError,
  nextPath = "/",
}: LoginShellProps) {
  const router = useRouter();
  const [password, setPassword] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState(initialError ?? null);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (!password.trim()) {
      return;
    }

    setPending(true);
    setError(null);

    try {
      const response = await fetch("/api/demo/access", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          password,
          next: nextPath,
        }),
      });

      const payload = (await response.json()) as {
        error?: string;
        nextPath?: string;
      };

      if (!response.ok) {
        throw new Error(payload.error ?? "Mot de passe invalide.");
      }

      router.push(payload.nextPath ?? nextPath);
      router.refresh();
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Impossible d'ouvrir l'acces demo.",
      );
    } finally {
      setPending(false);
    }
  }

  return (
    <main className="app-shell min-h-screen px-5 py-8 sm:px-8 lg:px-10">
      <section className="relative z-10 mx-auto flex min-h-[85vh] max-w-7xl items-center">
        <div className="grid w-full gap-6 lg:grid-cols-[1.1fr_0.9fr]">
          <div className="glass-card fade-in-up rounded-[32px] px-6 py-8 lg:px-8 lg:py-10">
            <span className="inline-flex items-center rounded-full border border-[rgba(23,117,186,0.16)] bg-[rgba(23,117,186,0.08)] px-3 py-1 text-sm font-semibold uppercase tracking-[0.22em] text-[var(--primary)]">
              {appConfig.appName}
            </span>
            <h1 className="mt-5 max-w-3xl text-4xl font-extrabold tracking-[-0.04em] text-[var(--ink)] sm:text-5xl">
              {appConfig.loginTitle}
            </h1>
            <p className="mt-5 max-w-2xl text-base leading-8 text-[var(--foreground)]">
              {appConfig.loginDescription}
            </p>

            <div className="mt-8 grid gap-4 md:grid-cols-3">
              {[
                {
                  title: "Catalogue YAML",
                  text: "Les cas pratiques et la base coach sont lus depuis des fichiers locaux editables.",
                },
                {
                  title: "Session navigateur",
                  text: "Onboarding, simulations, rapports et coach restent dans cette session de navigateur uniquement.",
                },
                {
                  title: "Demo partagee",
                  text: "Un seul mot de passe permet d'ouvrir l'environnement sans infrastructure d'authentification.",
                },
              ].map((item) => (
                <article
                  key={item.title}
                  className="rounded-[24px] border border-[var(--line)] bg-[var(--surface-soft)] p-5"
                >
                  <h2 className="text-lg font-bold text-[var(--ink)]">
                    {item.title}
                  </h2>
                  <p className="mt-3 text-sm leading-7 text-[var(--foreground)]">
                    {item.text}
                  </p>
                </article>
              ))}
            </div>
          </div>

          <div className="glass-card fade-in-up rounded-[32px] p-6 lg:p-8">
            <p className="text-sm font-semibold uppercase tracking-[0.22em] text-[var(--accent-red)]">
              Acces
            </p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.04em] text-[var(--ink)]">
              Entrer dans la demo
            </h2>
            <p className="mt-4 text-sm leading-7 text-[var(--foreground)]">
              Ouvrez la demo avec le mot de passe partage. Aucun compte
              individuel n&apos;est necessaire.
            </p>

            <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-4">
              <label
                className="text-sm font-semibold text-[var(--ink)]"
                htmlFor="password"
              >
                Mot de passe demo
              </label>
              <input
                id="password"
                type="password"
                autoComplete="current-password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                disabled={pending}
                placeholder="Mot de passe"
                className="rounded-[24px] border border-[var(--line)] bg-white px-5 py-4 text-sm text-[var(--ink)] outline-none transition-colors placeholder:text-[var(--foreground)]/70 focus:border-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-60"
              />

              {error ? (
                <div className="rounded-[24px] border border-[rgba(159,25,24,0.16)] bg-[rgba(159,25,24,0.06)] px-4 py-3 text-sm leading-7 text-[var(--accent-red)]">
                  {error}
                </div>
              ) : null}

              <button
                type="submit"
                disabled={pending || !password.trim()}
                className="mt-2 inline-flex items-center justify-center rounded-full bg-[var(--primary)] px-6 py-3 text-sm font-semibold text-white transition-colors hover:bg-[var(--primary-strong)] disabled:cursor-not-allowed disabled:opacity-60"
              >
                {pending ? "Ouverture..." : "Ouvrir la demo"}
              </button>
            </form>
          </div>
        </div>
      </section>
    </main>
  );
}
