"use client";

import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { logout } from "@/app/actions/auth";

const INACTIVITY_TIMEOUT_MS = 30 * 60 * 1000;

const navItems = [
  { href: "/admin", label: "Overview", exact: true },
  { href: "/admin/contacts", label: "Contact inbox" },
  { href: "/admin/admissions", label: "Admissions inbox" },
  { href: "/admin/homepage", label: "Homepage content" },
  { href: "/admin/programs", label: "Programs" },
  { href: "/admin/blogs", label: "Blog posts" },
];

export default function AdminShell({
  email,
  logoUrl,
  children,
}: {
  email: string;
  logoUrl: string;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);

  useEffect(() => {
    let timeoutId: ReturnType<typeof setTimeout>;

    const resetTimer = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        void logout();
      }, INACTIVITY_TIMEOUT_MS);
    };

    const activityEvents = ["pointerdown", "keydown", "scroll", "touchstart"];
    activityEvents.forEach((event) =>
      window.addEventListener(event, resetTimer, { passive: true }),
    );
    resetTimer();

    return () => {
      clearTimeout(timeoutId);
      activityEvents.forEach((event) =>
        window.removeEventListener(event, resetTimer),
      );
    };
  }, []);

  function isActive(href: string, exact?: boolean) {
    if (exact) return pathname === href;
    return pathname === href || pathname.startsWith(`${href}/`);
  }

  return (
    <div className="min-h-screen bg-[#f4f7ff] text-[#132b87]">
      <div className="lg:hidden sticky top-0 z-40 flex items-center justify-between border-b border-[#d9e2f7] bg-white px-4 py-3">
        <Image
          src={logoUrl}
          alt="Vido School logo"
          width={40}
          height={40}
          className="h-10 w-10 object-contain"
        />
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className="rounded-lg border border-[#d9e2f7] px-3 py-2 text-sm font-medium"
          aria-expanded={open}
        >
          Menu
        </button>
      </div>

      {open && (
        <button
          type="button"
          aria-label="Close navigation"
          onClick={() => setOpen(false)}
          className="fixed inset-0 top-16 z-20 bg-[#132b87]/20 lg:hidden"
        />
      )}

      <div className="flex min-h-[calc(100vh-65px)] w-full lg:min-h-screen">
        <aside
          className={`${
            open ? "flex" : "hidden"
          } fixed bottom-0 left-0 top-16 z-30 w-[min(20rem,88vw)] flex-col overflow-y-auto border-r border-[#d9e2f7] bg-white lg:top-0 lg:flex lg:h-screen lg:w-64 xl:w-72`}
        >
          <div className="hidden lg:flex flex-col items-start border-b border-[#d9e2f7] px-5 py-5">
            <Image
              src={logoUrl}
              alt="Vido School logo"
              width={64}
              height={64}
              className="h-16 w-16 object-contain"
            />
            <h1 className="mt-3 w-full text-left text-lg font-bold leading-tight">
              School Dashboard
            </h1>
            <p className="mt-2 w-full truncate text-left text-xs text-[#5a688d]">
              {email}
            </p>
          </div>

          <nav className="flex flex-col gap-1 p-3">
            {navItems.map((item) => {
              const active = isActive(item.href, item.exact);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className={`rounded-xl px-3 py-2.5 text-sm font-medium transition ${
                    active
                      ? "bg-[#1f3fb8] text-white"
                      : "text-[#3d4f84] hover:bg-[#eef3ff]"
                  }`}
                >
                  {item.label}
                </Link>
              );
            })}
          </nav>

          <div className="mt-auto border-t border-[#d9e2f7] p-3 space-y-2">
            <Link
              href="/"
              className="block rounded-xl px-3 py-2.5 text-sm font-medium text-[#3d4f84] hover:bg-[#eef3ff]"
            >
              View website
            </Link>
            <form action={logout}>
              <button
                type="submit"
                className="w-full rounded-xl px-3 py-2.5 text-left text-sm font-medium text-red-600 hover:bg-red-50"
              >
                Sign out
              </button>
            </form>
          </div>
        </aside>

        <main className="min-w-0 flex-1 p-4 sm:p-6 lg:ml-64 lg:p-8 xl:ml-72 xl:p-10 2xl:p-12">
          <div className="w-full">{children}</div>
        </main>
      </div>
    </div>
  );
}
