"use client";

import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
import { userMessage } from "../lib/messages";

const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL || "/api/v1";

export default function AccessPage() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [challenge, setChallenge] = useState("");

  useEffect(() => {
    const reason = new URLSearchParams(window.location.search).get("motivo");
    if (reason !== "sesion-expirada") return;
    const timer = window.setTimeout(() =>
      setNotice("Tu sesión terminó por inactividad. Inicia sesión nuevamente para continuar."), 0);
    return () => window.clearTimeout(timer);
  }, []);

  async function enterPanel(csrfToken: string) {
    sessionStorage.setItem("documenta:csrf", csrfToken);
    const verification = await fetch(`${apiBase}/auth/me`, { credentials: "include", cache: "no-store" });
    if (!verification.ok) {
      sessionStorage.removeItem("documenta:csrf");
      throw new Error("La sesión no pudo establecerse. Revisa que el navegador permita cookies seguras.");
    }
    const destinations: Record<string,string> = {
      "personas.documenta.cl": "/personas",
      "pro.documenta.cl": "/pro",
    };
    window.location.replace(destinations[window.location.hostname] || "/panel");
  }

  async function login(event: FormEvent<HTMLFormElement>) {
    event.preventDefault(); setLoading(true); setError("");
    const form = new FormData(event.currentTarget);
    try {
      const response = await fetch(`${apiBase}/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ email: form.get("email"), password: form.get("password") }) });
      const data = await response.json();
      if (!response.ok) throw new Error(data.detail || "No fue posible iniciar sesión.");
      if (data.mfa_required) { setChallenge(data.challenge_token); return; }
      await enterPanel(data.csrf_token);
    } catch (reason) { setError(userMessage(reason, "No fue posible iniciar sesión.")); }
    finally { setLoading(false); }
  }

  async function verify(event: FormEvent<HTMLFormElement>) {
    event.preventDefault(); setLoading(true); setError("");
    const form = new FormData(event.currentTarget);
    try {
      const response = await fetch(`${apiBase}/auth/mfa/verify`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ challenge_token: challenge, code: form.get("code") }) });
      const data = await response.json();
      if (!response.ok) throw new Error(data.detail || "Código incorrecto.");
      await enterPanel(data.csrf_token);
    } catch (reason) { setError(userMessage(reason, "No fue posible verificar el código.")); }
    finally { setLoading(false); }
  }

  return <main className="auth-page"><section className="auth-card">
    <Link href="/" className="auth-logo"><img src="/media/brand/logo-horizontal.svg" alt="Documenta" width="178" /></Link>
    <span className="section-kicker">Acceso seguro</span>
    <h1>{challenge ? "Verifica tu identidad" : "Bienvenido a Documenta"}</h1>
    <p>{challenge ? "Ingresa el código de seis dígitos de tu aplicación de autenticación." : "Consulta documentos, solicitudes y configuraciones de tu cuenta."}</p>
    {notice && <div className="success-note" role="status">{notice}</div>}
    {!challenge ? <form className="auth-form" onSubmit={login}>
      <label>Correo electrónico<input name="email" type="email" required autoComplete="email" /></label>
      <label>Contraseña<input name="password" type="password" required autoComplete="current-password" /></label>
      <Link className="text-link" href="/acceso/recuperar">¿Olvidaste tu contraseña?</Link>
      {error && <div className="form-error" role="alert">{error}</div>}
      <button className="button button-primary" disabled={loading}>{loading ? "Ingresando…" : "Iniciar sesión"}</button>
    </form> : <form className="auth-form" onSubmit={verify}>
      <label>Código 2FA o recuperación<input name="code" maxLength={20} required autoComplete="one-time-code" /></label>
      {error && <div className="form-error" role="alert">{error}</div>}
      <button className="button button-primary" disabled={loading}>{loading ? "Verificando…" : "Verificar y entrar"}</button>
      <button className="text-link" type="button" onClick={() => { setChallenge(""); setError(""); }}>Volver al acceso</button>
    </form>}
    <small className="auth-footnote">La cuenta del cliente es opcional. Puedes crearla después de iniciar un trámite.</small>
  </section></main>;
}
