import { FormEvent, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";

import { getTenantDefaultPath } from "../config/workspace";
import { usePortalSession } from "../context/PortalSessionContext";
import { fetchAuthStatus } from "../lib/api";
import { portalRuntimeConfig } from "../config/runtime";

const defaultLoginForm = {
  identifier: "",
  password: ""
};

const defaultBootstrapForm = {
  password: ""
};

export function LoginPage() {
  const navigate = useNavigate();
  const { bootstrap, currentUser, login, platformAdmin, status } = usePortalSession();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [systemNote, setSystemNote] = useState("Carico lo stato del gestionale.");
  const [bootstrapRequired, setBootstrapRequired] = useState(false);
  const [superAdminIdentifier, setSuperAdminIdentifier] = useState("zanchinfede@gmail.com");
  const [loginForm, setLoginForm] = useState(defaultLoginForm);
  const [bootstrapForm, setBootstrapForm] = useState(defaultBootstrapForm);

  useEffect(() => {
    if (status === "authenticated") {
      navigate(
        platformAdmin?.is_super_admin && !platformAdmin.is_impersonating
          ? "/admin"
          : getTenantDefaultPath(currentUser?.role, currentUser?.permissions),
        {
          replace: true
        }
      );
    }
  }, [currentUser?.permissions, currentUser?.role, navigate, platformAdmin, status]);

  useEffect(() => {
    async function loadAuthStatus() {
      try {
        const payload = await fetchAuthStatus(portalRuntimeConfig.apiHubBaseUrl);
        setBootstrapRequired(Boolean(payload.super_admin_bootstrap_required));
        setSuperAdminIdentifier(payload.super_admin_identifier || "zanchinfede@gmail.com");
        if (payload.super_admin_bootstrap_required) {
          setSystemNote("Prima attivazione: imposta la password del super admin.");
          return;
        }

        setSystemNote(`${payload.tenant_count} locali clienti registrati e ${payload.user_count} utenti admin attivi.`);
      } catch {
        setSystemNote("Backend raggiungibile in modo parziale. Puoi comunque provare ad accedere.");
      }
    }

    void loadAuthStatus();
  }, []);

  async function handleLoginSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setBusy(true);
    setError(null);

    try {
      const response = await login(loginForm);
      navigate(
        response.platform_admin?.is_super_admin && !response.platform_admin.is_impersonating
          ? "/admin"
          : "/home",
        { replace: true }
      );
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : "Accesso non riuscito.");
    } finally {
      setBusy(false);
    }
  }

  async function handleBootstrapSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setBusy(true);
    setError(null);

    try {
      await bootstrap(bootstrapForm);
      navigate("/admin", { replace: true });
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : "Configurazione iniziale non riuscita.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <section className="portal-frame auth-root">
      <div className="portal-background" />

      <main className="auth-stage">
        <section className="auth-side">
          <div className="auth-brand">
            <div className="auth-brand-mark">PU</div>
            <div>
              <strong>PowerUp Suite</strong>
              <span>Hospitality operations</span>
            </div>
          </div>

          <div className="auth-copy">
            <p className="eyebrow">Accesso riservato</p>
            <h1 className="auth-heading">Una regia unica per locale, moduli e documenti.</h1>
            <p className="muted-copy">
              Interfaccia operativa compatta, tenant separati e strumenti del locale raggiungibili in pochi secondi.
            </p>
          </div>
        </section>

        <section className="panel auth-card stack-md">
          {bootstrapRequired ? (
            <form className="mock-form auth-form" onSubmit={handleBootstrapSubmit}>
              <div className="stack-sm">
                <p className="eyebrow">Bootstrap</p>
                <h2 className="page-title">Imposta il super admin</h2>
                <p className="muted-copy">
                  Primo accesso piattaforma. L&apos;utente amministratore principale sara <strong>{superAdminIdentifier}</strong>.
                </p>
              </div>

              <label className="field">
                <span>Password iniziale super admin</span>
                <input
                  type="password"
                  value={bootstrapForm.password}
                  onChange={(event) => setBootstrapForm({ password: event.target.value })}
                  placeholder="Almeno 8 caratteri"
                  required
                  minLength={8}
                  disabled={busy}
                />
              </label>

              <button type="submit" className="button-primary" disabled={busy}>
                {busy ? "Configurazione in corso" : "Attiva super admin"}
              </button>
            </form>
          ) : (
            <form className="mock-form auth-form" onSubmit={handleLoginSubmit}>
              <div className="stack-sm">
                <p className="eyebrow">Portale</p>
                <h2 className="page-title">Accedi al workspace</h2>
                <p className="muted-copy">
                  Usa questa stessa schermata sia per il super admin sia per gli account admin dei singoli locali.
                </p>
              </div>

              <label className="field">
                <span>Username o email</span>
                <input
                  type="text"
                  value={loginForm.identifier}
                  onChange={(event) => setLoginForm((current) => ({ ...current, identifier: event.target.value }))}
                  placeholder="admin@locale.it oppure admin_locale"
                  required
                  minLength={3}
                  disabled={busy}
                />
              </label>

              <label className="field">
                <span>Password</span>
                <input
                  type="password"
                  value={loginForm.password}
                  onChange={(event) => setLoginForm((current) => ({ ...current, password: event.target.value }))}
                  placeholder="Password amministratore"
                  required
                  disabled={busy}
                />
              </label>

              <button type="submit" className="button-primary" disabled={busy}>
                {busy ? "Accesso in corso" : "Entra nel portale"}
              </button>
            </form>
          )}

          {error ? <p className="auth-error">{error}</p> : null}
          {!error ? <p className="muted-copy">{systemNote}</p> : null}

          <div className="auth-footer-links">
            <Link to="/privacy">Privacy</Link>
            <Link to="/terms">Termini</Link>
            <Link to="/data-deletion">Dati</Link>
          </div>
        </section>
      </main>
    </section>
  );
}
