"use client";

import { useEffect, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { api, getMsgReadAt, markMsgRead } from "@/lib/client";

export interface Me {
  id: string;
  role: string;
  branchId: string | null;
  branchName: string | null;
  name: string;
  email: string;
}

const ROLE_LABEL: Record<string, string> = {
  super_admin: "Super Admin",
  owner_approver: "Pemilik Usaha",
  branch_admin: "Admin Cabang",
  courier: "Kurir",
};

const NAV_ITEMS: { href: string; label: string; roles: string[] }[] = [
  { href: "/dashboard", label: "Beranda", roles: ["super_admin", "owner_approver"] },
  { href: "/admin/branches", label: "Cabang", roles: ["super_admin"] },
  { href: "/admin/users", label: "Akun", roles: ["super_admin"] },
  { href: "/admin/deliveries", label: "Pengiriman", roles: ["super_admin", "owner_approver"] },
  { href: "/admin/flagged-adjustments", label: "Cek Penyesuaian Stok", roles: ["super_admin"] },
  { href: "/admin/audit", label: "Riwayat Aktivitas", roles: ["super_admin", "owner_approver"] },
  { href: "/admin/reports", label: "Laporan", roles: ["super_admin"] },
];

export default function AppShell({
  title,
  children,
  onMe,
}: {
  title: string;
  children: React.ReactNode;
  onMe?: (me: Me) => void;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [me, setMe] = useState<Me | null>(null);

  useEffect(() => {
    api<Me>("/api/auth/me")
      .then((m) => {
        setMe(m);
        onMe?.(m);
      })
      .catch(() => router.push("/login"));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function logout() {
    await api("/api/auth/logout", { method: "POST" });
    router.push("/login");
    router.refresh();
  }

  return (
    <div className="min-h-screen">
      <header className="sticky top-0 z-10 border-b border-slate-200 bg-white">
        <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-3">
          <div className="flex items-center gap-2">
            <span className="text-xl">🥚</span>
            <div>
              <h1 className="text-sm font-bold leading-tight">{title}</h1>
              {me && (
                <p className="text-xs text-slate-500">
                  {me.name} · {ROLE_LABEL[me.role] ?? me.role}
                  {me.branchName ? ` · ${me.branchName}` : ""}
                </p>
              )}
            </div>
          </div>
          <div className="flex items-center gap-2">
            {me && <NotifBell me={me} />}
            <button onClick={logout} className="btn-outline text-xs">
              Keluar
            </button>
          </div>
        </div>
        {me && NAV_ITEMS.some((n) => n.roles.includes(me.role)) && (
          <nav className="mx-auto flex max-w-6xl gap-1 overflow-x-auto px-4 pb-2">
            {NAV_ITEMS.filter((n) => n.roles.includes(me.role)).map((n) => (
              <Link
                key={n.href}
                href={n.href}
                className={`whitespace-nowrap rounded px-3 py-1.5 text-xs font-medium ${
                  pathname === n.href
                    ? "bg-brand-600 text-white"
                    : "text-slate-600 hover:bg-slate-100"
                }`}
              >
                {n.label}
              </Link>
            ))}
          </nav>
        )}
      </header>
      <main className="mx-auto max-w-6xl px-4 py-5">{children}</main>
    </div>
  );
}

// Lonceng notifikasi pesan (Pusat ↔ Admin Cabang). Badge merah = jumlah pesan
// masuk yang belum dibaca; klik → tandai dibaca & buka area pesan.
function NotifBell({ me }: { me: Me }) {
  const [count, setCount] = useState(0);
  const canSee = ["super_admin", "owner_approver", "branch_admin"].includes(me.role);

  useEffect(() => {
    if (!canSee) return;
    const load = () =>
      api<{ count: number }>(`/api/messages/unread?since=${encodeURIComponent(getMsgReadAt(me.id))}`)
        .then((r) => setCount(r.count))
        .catch(() => {});
    load();
    const t = setInterval(load, 15000);
    return () => clearInterval(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [me.id, canSee]);

  if (!canSee) return null;

  function open() {
    markMsgRead(me.id);
    setCount(0);
    if (me.role === "branch_admin") {
      if (window.location.pathname === "/branch") {
        window.dispatchEvent(new CustomEvent("open-pesan"));
      } else {
        window.location.href = "/branch?tab=pesan";
      }
    } else {
      if (window.location.pathname === "/dashboard") {
        document.getElementById("pesan")?.scrollIntoView({ behavior: "smooth" });
      } else {
        window.location.href = "/dashboard#pesan";
      }
    }
  }

  return (
    <button
      onClick={open}
      title={count > 0 ? `${count} pesan belum dibaca` : "Tidak ada pesan baru"}
      className="relative rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-sm hover:bg-slate-100"
    >
      🔔
      {count > 0 && (
        <span className="absolute -right-1.5 -top-1.5 flex h-5 min-w-5 items-center justify-center rounded-full bg-red-600 px-1 text-[10px] font-bold text-white">
          {count > 99 ? "99+" : count}
        </span>
      )}
    </button>
  );
}
