import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";
import { ReactNode } from "react";
import { LogOut, Home, UserRound } from "lucide-react";
import { getFullUser } from "@/lib/auth";
import { logout } from "@/lib/actions";
import { NavList, NavItem } from "@/components/nav-list";
import { jNowFormatted } from "@/lib/jalali";

const ROLE_LABEL: Record<string, string> = { admin: "مدیریت مدرسه", teacher: "دبیر", student: "دانش‌آموز" };

export async function PanelShell({ role, items, children }: { role: string; items: NavItem[]; children: ReactNode }) {
  const u = await getFullUser();
  if (!u || u.role !== role) redirect("/login");
  if (u.mustChangePassword) redirect("/change-password");

  return (
    <div className="min-h-screen bg-transparent">
      {/* نوار بالا */}
      <header className="sticky top-0 z-40 border-b border-emerald-900/10 bg-white/85 backdrop-blur-lg">
        <div className="mx-auto flex max-w-[1500px] items-center justify-between gap-3 px-4 py-2.5">
          <div className="flex items-center gap-3">
            <Link href="/" className="flex items-center gap-2.5">
              <Image src="/images/logo.png" alt="لوگو" width={38} height={38} className="rounded-full shadow" />
              <div className="hidden sm:block">
                <div className="text-[13px] font-black text-emerald-950">مدرسهٔ شهید باهنر ملوران</div>
                <div className="text-[10px] font-bold text-emerald-800/60">{ROLE_LABEL[role]}</div>
              </div>
            </Link>
          </div>
          <div className="flex items-center gap-2">
            <span className="hidden text-[11px] font-bold text-emerald-800/60 md:block">{jNowFormatted()}</span>
            <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-900/5 px-3 py-1.5 text-xs font-extrabold text-emerald-900">
              <UserRound size={13} className="text-emerald-700" /> {u.firstName} {u.lastName}
            </span>
            <Link href="/" title="صفحهٔ اصلی" className="grid size-9 place-items-center rounded-xl border border-emerald-900/10 text-emerald-800 transition hover:bg-emerald-50"><Home size={16} /></Link>
            <form action={logout}>
              <button title="خروج" className="grid size-9 place-items-center rounded-xl bg-red-50 text-red-600 transition hover:bg-red-100"><LogOut size={16} /></button>
            </form>
          </div>
        </div>
      </header>

      <div className="mx-auto grid max-w-[1500px] gap-0 lg:grid-cols-[240px_1fr]">
        {/* سایدبار */}
        <aside className="border-b border-emerald-900/10 bg-white/60 py-3 lg:min-h-[calc(100vh-58px)] lg:border-b-0 lg:border-l lg:py-6 lg:pl-4 lg:pr-3">
          <NavList items={items} />
        </aside>
        {/* محتوا */}
        <main className="min-w-0 px-4 py-6 lg:px-7">{children}</main>
      </div>
    </div>
  );
}
