"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import {
  Activity,
  BarChart3,
  Bell,
  Building2,
  ChevronDown,
  DatabaseBackup,
  FileText,
  Gauge,
  Headset,
  LayoutDashboard,
  LogOut,
  Mail,
  Menu,
  Network,
  Package,
  Radio,
  Receipt,
  ServerCog,
  Settings,
  ShieldCheck,
  Users,
  Wallet,
  X,
} from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, cn } from "@/components/ui";
import { initials } from "@/lib/utils";

export interface ShellUser {
  id: number;
  name: string;
  email: string;
  roleSlug: string;
  roleName: string;
  permissions: string[];
}

interface NavItem {
  label: string;
  href: string;
  icon: React.ReactNode;
  permission?: string;
}

interface NavGroup {
  title: string;
  items: NavItem[];
}

const NAV: NavGroup[] = [
  {
    title: "Overview",
    items: [{ label: "Dashboard", href: "/admin", icon: <LayoutDashboard className="h-4 w-4" />, permission: "dashboard.view" }],
  },
  {
    title: "Customers",
    items: [
      { label: "Customers", href: "/admin/customers", icon: <Users className="h-4 w-4" />, permission: "customers.view" },
      { label: "Packages", href: "/admin/packages", icon: <Package className="h-4 w-4" />, permission: "packages.view" },
      { label: "Employees", href: "/admin/employees", icon: <Headset className="h-4 w-4" />, permission: "employees.view" },
    ],
  },
  {
    title: "Network",
    items: [
      { label: "Routers", href: "/admin/routers", icon: <ServerCog className="h-4 w-4" />, permission: "routers.view" },
      { label: "MikroTik / PPPoE", href: "/admin/mikrotik", icon: <Radio className="h-4 w-4" />, permission: "mikrotik.view" },
      { label: "OLT / ONU", href: "/admin/olt", icon: <Network className="h-4 w-4" />, permission: "olt.view" },
    ],
  },
  {
    title: "Billing",
    items: [
      { label: "Bills & Invoices", href: "/admin/billing", icon: <FileText className="h-4 w-4" />, permission: "billing.view" },
      { label: "Payments", href: "/admin/payments", icon: <Wallet className="h-4 w-4" />, permission: "payments.view" },
      { label: "Support Tickets", href: "/admin/tickets", icon: <Building2 className="h-4 w-4" />, permission: "tickets.view" },
    ],
  },
  {
    title: "Insights",
    items: [
      { label: "Reports", href: "/admin/reports", icon: <BarChart3 className="h-4 w-4" />, permission: "reports.view" },
      { label: "Activity Logs", href: "/admin/logs", icon: <Activity className="h-4 w-4" />, permission: "logs.view" },
      { label: "Messages", href: "/admin/messages", icon: <Mail className="h-4 w-4" />, permission: "sms.view" },
    ],
  },
  {
    title: "System",
    items: [
      { label: "Users & Roles", href: "/admin/users", icon: <ShieldCheck className="h-4 w-4" />, permission: "users.view" },
      { label: "Backups", href: "/admin/backups", icon: <DatabaseBackup className="h-4 w-4" />, permission: "backup.view" },
      { label: "Settings", href: "/admin/settings", icon: <Settings className="h-4 w-4" />, permission: "settings.view" },
    ],
  },
];

function Clock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);
  return (
    <div className="hidden text-right leading-tight lg:block">
      <p className="font-mono text-sm font-semibold text-slate-100 tabular-nums">
        {now.toLocaleTimeString("en-GB", { hour12: false })}
      </p>
      <p className="text-[10px] uppercase tracking-wider text-slate-500">
        {now.toLocaleDateString("en-GB", { weekday: "short", day: "2-digit", month: "short" })}
      </p>
    </div>
  );
}

function NotificationBell() {
  const { data, reload } = useApi<{ items: { id: number; title: string; message?: string | null; level: string; link?: string | null; readAt: string | null; createdAt: string }[]; unread: number }>(
    "/api/notifications",
  );
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const timer = setInterval(() => void reload(), 60_000);
    return () => clearInterval(timer);
  }, [reload]);

  const unread = data?.unread ?? 0;

  return (
    <div className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        className="relative grid h-9 w-9 place-items-center rounded-xl border border-white/10 bg-white/5 text-slate-300 transition hover:bg-white/10 hover:text-slate-100"
        aria-label="Notifications"
      >
        <Bell className="h-4 w-4" />
        {unread > 0 ? (
          <span className="absolute -right-1 -top-1 grid h-4 min-w-4 place-items-center rounded-full bg-rose-500 px-1 text-[10px] font-bold text-white">
            {unread > 9 ? "9+" : unread}
          </span>
        ) : null}
      </button>
      {open ? (
        <div className="glass-strong absolute right-0 z-50 mt-2 w-[min(92vw,22rem)] rounded-2xl p-2 shadow-2xl">
          <div className="flex items-center justify-between px-2 py-1.5">
            <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">Notification centre</p>
            <button
              className="text-[11px] text-brand-400 hover:underline"
              onClick={async () => {
                await api("/api/notifications", { method: "POST", json: {} });
                setOpen(false);
                void reload();
              }}
            >
              Mark all read
            </button>
          </div>
          <div className="max-h-80 overflow-y-auto">
            {(data?.items ?? []).slice(0, 12).map((n) => (
              <Link
                key={n.id}
                href={n.link || "#"}
                onClick={() => setOpen(false)}
                className={cn(
                  "block rounded-xl px-2.5 py-2 transition hover:bg-white/6",
                  n.readAt ? "opacity-60" : "bg-brand-500/6",
                )}
              >
                <div className="flex items-center justify-between gap-2">
                  <p className="truncate text-xs font-semibold text-slate-100">{n.title}</p>
                  <Badge value={n.level === "danger" ? "expired" : n.level === "warning" ? "due" : n.level === "success" ? "active" : "unknown"} label={n.level} />
                </div>
                {n.message ? <p className="mt-0.5 line-clamp-2 text-[11px] text-slate-400">{n.message}</p> : null}
              </Link>
            ))}
            {(data?.items ?? []).length === 0 ? <p className="px-3 py-6 text-center text-xs text-slate-500">No notifications</p> : null}
          </div>
        </div>
      ) : null}
    </div>
  );
}

export function AdminShell({ user, children }: { user: ShellUser; children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [userOpen, setUserOpen] = useState(false);

  useEffect(() => {
    setMobileOpen(false);
    setUserOpen(false);
  }, [pathname]);

  const groups = useMemo(
    () =>
      NAV.map((group) => ({
        ...group,
        items: group.items.filter((item) => !item.permission || user.roleSlug === "super_admin" || user.permissions.includes(item.permission)),
      })).filter((group) => group.items.length > 0),
    [user],
  );

  const logout = async () => {
    await api("/api/auth/logout", { method: "POST" });
    router.replace("/login");
    router.refresh();
  };

  const sidebar = (
    <div className="flex h-full flex-col">
      <div className="flex items-center gap-3 border-b border-white/8 px-5 py-4">
        <span className="grid h-10 w-10 place-items-center rounded-xl bg-gradient-to-br from-brand-500 to-cyan-400 text-sm font-bold text-ink-950">IS</span>
        <div>
          <p className="text-sm font-bold tracking-wide text-slate-50">ISP DIGITAL</p>
          <p className="text-[10px] uppercase tracking-[0.18em] text-slate-500">Management Suite</p>
        </div>
      </div>

      <nav className="flex-1 space-y-5 overflow-y-auto px-3 py-4">
        {groups.map((group) => (
          <div key={group.title}>
            <p className="px-2 pb-1.5 text-[10px] font-bold uppercase tracking-[0.16em] text-slate-600">{group.title}</p>
            <div className="space-y-0.5">
              {group.items.map((item) => {
                const active = item.href === "/admin" ? pathname === "/admin" : pathname.startsWith(item.href);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={cn(
                      "flex items-center gap-3 rounded-xl px-3 py-2 text-sm transition",
                      active
                        ? "bg-gradient-to-r from-brand-500/22 to-transparent text-slate-50 ring-1 ring-inset ring-brand-400/25"
                        : "text-slate-400 hover:bg-white/6 hover:text-slate-100",
                    )}
                  >
                    <span className={active ? "text-brand-400" : "text-slate-500"}>{item.icon}</span>
                    {item.label}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      <div className="border-t border-white/8 px-4 py-3">
        <div className="glass rounded-xl p-3">
          <div className="flex items-center gap-2 text-xs text-slate-300">
            <Gauge className="h-4 w-4 text-emerald-400" />
            <span className="font-semibold">System operational</span>
          </div>
          <p className="mt-1 text-[11px] text-slate-500">Cron automation & MikroTik sync active</p>
        </div>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen">
      <aside className="fixed inset-y-0 left-0 z-40 hidden w-64 border-r border-white/8 bg-ink-900/70 backdrop-blur-xl lg:block">{sidebar}</aside>

      {mobileOpen ? (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-ink-950/80 backdrop-blur-sm" onClick={() => setMobileOpen(false)} />
          <aside className="glass-strong animate-fade-up absolute inset-y-0 left-0 w-72 border-r border-white/10">{sidebar}</aside>
        </div>
      ) : null}

      <div className="lg:pl-64">
        <header className="sticky top-0 z-30 border-b border-white/8 bg-ink-950/80 backdrop-blur-xl">
          <div className="flex items-center justify-between gap-3 px-4 py-3 sm:px-6">
            <div className="flex items-center gap-3">
              <button
                className="grid h-9 w-9 place-items-center rounded-xl border border-white/10 bg-white/5 text-slate-300 lg:hidden"
                onClick={() => setMobileOpen(true)}
                aria-label="Open menu"
              >
                {mobileOpen ? <X className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
              </button>
              <div>
                <p className="text-sm font-semibold text-slate-100">Welcome back, {user.name.split(" ")[0]}</p>
                <p className="text-[11px] text-slate-500">{user.roleName} · ISP DIGITAL</p>
              </div>
            </div>

            <div className="flex items-center gap-2 sm:gap-3">
              <Clock />
              <NotificationBell />
              <div className="relative">
                <button
                  onClick={() => setUserOpen((v) => !v)}
                  className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 py-1.5 pl-1.5 pr-2.5 transition hover:bg-white/10"
                >
                  <span className="grid h-7 w-7 place-items-center rounded-lg bg-gradient-to-br from-brand-500 to-cyan-400 text-[11px] font-bold text-ink-950">
                    {initials(user.name)}
                  </span>
                  <span className="hidden text-xs font-medium text-slate-200 sm:block">{user.name}</span>
                  <ChevronDown className="h-3.5 w-3.5 text-slate-400" />
                </button>
                {userOpen ? (
                  <div className="glass-strong absolute right-0 z-50 mt-2 w-56 rounded-2xl p-2">
                    <div className="border-b border-white/10 px-2.5 py-2">
                      <p className="text-sm font-semibold text-slate-100">{user.name}</p>
                      <p className="truncate text-[11px] text-slate-500">{user.email}</p>
                    </div>
                    <Link href="/admin/settings" className="flex items-center gap-2 rounded-lg px-2.5 py-2 text-xs text-slate-300 hover:bg-white/6">
                      <Settings className="h-3.5 w-3.5" /> Settings & profile
                    </Link>
                    <Link href="/admin/logs" className="flex items-center gap-2 rounded-lg px-2.5 py-2 text-xs text-slate-300 hover:bg-white/6">
                      <Receipt className="h-3.5 w-3.5" /> Activity log
                    </Link>
                    <button onClick={logout} className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-xs text-rose-300 hover:bg-rose-500/10">
                      <LogOut className="h-3.5 w-3.5" /> Secure logout
                    </button>
                  </div>
                ) : null}
              </div>
            </div>
          </div>
        </header>

        <main className="px-4 py-5 sm:px-6 lg:py-7">{children}</main>

        <footer className="px-4 pb-6 pt-2 text-center text-[11px] text-slate-600 sm:px-6">
          ISP DIGITAL · Billing, MikroTik automation & support platform
        </footer>
      </div>
    </div>
  );
}
