"use client";

import Image from "next/image";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { getApiUrl, loadSession, saveSession, type SessionPayload } from "@/lib/auth";
import styles from "./page.module.css";

export default function Home() {
  const router = useRouter();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  const apiUrl = getApiUrl();

  useEffect(() => {
    const session = loadSession();
    if (!session) {
      return;
    }

    if (session.user.role === "ADMIN") {
      router.replace("/admin");
      return;
    }

    router.replace("/predictions");
  }, [router]);

  const canSubmit = useMemo(
    () => username.trim().length > 2 && password.length >= 8,
    [password.length, username],
  );

  const submitLogin = async () => {
    setLoading(true);
    setMessage("");

    try {
      const response = await fetch(`${apiUrl}/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });

      const payload = (await response.json()) as
        | SessionPayload
        | { message?: string };

      if (
        !response.ok ||
        !("accessToken" in payload) ||
        !("refreshToken" in payload)
      ) {
        setMessage((payload as { message?: string }).message ?? "Identifiants invalides");
        return;
      }

      saveSession(payload);

      if (payload.user.role === "ADMIN") {
        router.push("/admin");
        return;
      }

      router.push("/predictions");
    } catch {
      setMessage("Erreur reseau, impossible de contacter l'API");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className={`app-shell ${styles.page}`}>
      <section className={styles.loginShell} aria-labelledby="login-title">
        <div className={styles.visualPanel}>
          <Image
            src="/depotARanger/baniere-deco-gauche-haut.png"
            alt=""
            width={132}
            height={132}
            className={`${styles.cornerDeco} ${styles.cornerDecoLeft}`}
            aria-hidden="true"
          />
          <Image
            src="/depotARanger/baniere-deco-droite-haut.png"
            alt=""
            width={150}
            height={150}
            className={`${styles.cornerDeco} ${styles.cornerDecoRight}`}
            aria-hidden="true"
          />

          <div className={styles.cloudBadge}>
            <Image
              src="/depotARanger/bebe-sur-un-nuage.png"
              alt="Bubulle sur un nuage"
              width={220}
              height={220}
              className={styles.cloudBaby}
              priority
            />
          </div>

          <div className={styles.visualCopy}>
            <span>Bienvenue !</span>
            <h1 id="login-title">Le Juste Poids</h1>
            <p>Amusez-vous à pronostiquer l&apos;arrivée de Bubulle !</p>
          </div>

          <div className={styles.balanceStage}>
            <Image
              src="/depotARanger/bebe-sur-une-balance-girl.png"
              alt="Bubulle sur la balance"
              width={460}
              height={420}
              className={styles.balanceBaby}
              priority
            />
          </div>
        </div>

        <section className={styles.loginPanel} aria-label="Connexion">
          <div className={styles.loginIntro}>
            <span>Accès pronostics</span>
            <h2>Connexion</h2>
          </div>
          <form
            onSubmit={(event) => {
              event.preventDefault();
              void submitLogin();
            }}
            className={styles.form}
          >
            <div className="field">
              <label htmlFor="username">Nom d&apos;utilisateur</label>
              <input
                id="username"
                value={username}
                onChange={(event) => setUsername(event.target.value)}
                placeholder="Votre nom d'utilisateur"
                autoComplete="username"
                />
            </div>
            <div className="field">
              <label htmlFor="password">Mot de passe</label>
              <input
                id="password"
                type="password"
                value={password}
                placeholder="Votre mot de passe"
                onChange={(event) => setPassword(event.target.value)}
                autoComplete="current-password"
              />
            </div>
            <button className={`btn btn-primary ${styles.submitButton}`} disabled={!canSubmit || loading}>
              {loading ? "Connexion..." : "Connexion"}
            </button>
          </form>
          {message ? <p className={styles.message}>{message}</p> : null}
        </section>
      </section>
    </main>
  );
}
