"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import {
  getApiUrl,
  loadSession,
  logoutSession,
  type AuthUser,
} from "@/lib/auth";
import styles from "@/features/predictions/styles/predictions.module.css";
import {
  PredictionThemeProvider,
  usePredictionTheme,
} from "@/features/predictions/context/prediction-theme-context";

type PredictionsLayoutProps = {
  children: React.ReactNode;
};

const BURGER_LINKS = [
  { href: "/predictions", label: "Page Principale", exact: true },
  { href: "/predictions/history", label: "Historique", exact: true },
  { href: "/profile", label: "Mon profil", exact: false },
];

export default function PredictionsLayout({ children }: PredictionsLayoutProps) {
  return (
    <PredictionThemeProvider>
      <PredictionsLayoutContent>{children}</PredictionsLayoutContent>
    </PredictionThemeProvider>
  );
}

function PredictionsLayoutContent({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [user, setUser] = useState<AuthUser | null>(null);
  const [ready, setReady] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const { theme } = usePredictionTheme();

  const logoSrc =
    theme === "girl"
      ? "/depotARanger/bebe-sur-un-nuage-girl.png"
      : "/depotARanger/bebe-sur-un-nuage.png";

  useEffect(() => {
    if (!menuOpen) return;
    function handleClickOutside(e: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [menuOpen]);

  useEffect(() => {
    const session = loadSession();

    if (!session) {
      router.replace("/");
      return;
    }

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

    setUser(session.user);
    setReady(true);
  }, [router]);

  const onLogout = async () => {
    await logoutSession(getApiUrl());
    window.location.replace("/");
  };

  if (!ready) {
    return (
      <main className="app-shell">
        <section className={styles.loadingScreen}>
          <Image src="/images/icons/logo.png" alt="Le Juste Poids" width={80} height={80} />
          <p>Chargement...</p>
        </section>
      </main>
    );
  }

  return (
    <main className="app-shell">
      {/* Header bar */}
      <header className={styles.appHeader}>
        <div className={styles.appHeaderLeft}>
          <Image src={logoSrc} alt="Logo" width={50} height={50} className={styles.headerLogo} />
          <span className={styles.appTitle}>Le juste poids</span>
        </div>
        <div className={styles.menuWrapper} ref={menuRef}>
          <button
            className={styles.burgerBtn}
            onClick={() => setMenuOpen(!menuOpen)}
            aria-label="Menu"
            type="button"
          >
            <span className={styles.burgerLine} />
            <span className={styles.burgerLine} />
            <span className={styles.burgerLine} />
          </button>

          {menuOpen && (
            <nav className={styles.mobileMenu}>
              {BURGER_LINKS.filter(({ href, exact }) => {
                const isCurrentPage = exact ? pathname === href : pathname.startsWith(href);
                return !isCurrentPage;
              }).map(({ href, label }) => (
                <Link
                  key={href}
                  className={styles.tab}
                  href={href}
                  onClick={() => setMenuOpen(false)}
                >
                  {label}
                </Link>
              ))}
              <div className={styles.menuDivider} />
              <button type="button" className={`btn btn-soft ${styles.logoutBtn}`} onClick={onLogout}>Se déconnecter</button>
            </nav>
          )}
        </div>
      </header>

      {/* Main tab bar — rendered inline in each page */}

      <div className={styles.page}>
        {children}
      </div>
    </main>
  );
}
