"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { signOut } from "next-auth/react";
import {
  LayoutDashboard,
  Gauge,
  ListChecks,
  CalendarClock,
  CalendarCheck,
  Target,
  BarChart3,
  FileBarChart,
  ClipboardCheck,
  Users,
  Settings,
  LogOut,
  Menu,
} from "lucide-react";
import { cn, initials } from "@/lib/utils";
import { can, ROLE_LABELS, type Permission } from "@/lib/rbac";
import type { Role } from "@/lib/types";
import { ThemeToggle } from "@/components/theme-toggle";

type NavItem = {
  href: string;
  label: string;
  icon: React.ComponentType<{ className?: string }>;
  perm?: Permission;
};

const NAV: NavItem[] = [
  { href: "/dashboard", label: "Dashboard", icon: LayoutDashboard },
  { href: "/executive", label: "Executive", icon: Gauge, perm: "dashboard:viewTeam" },
  { href: "/tasks", label: "Tasks", icon: ListChecks },
  { href: "/weekly", label: "Weekly Log", icon: CalendarClock },
  { href: "/posts", label: "Content Calendar", icon: CalendarCheck, perm: "posts:read" },
  { href: "/kpis", label: "KPI Indicators", icon: Target },
  { href: "/reports", label: "Reports", icon: BarChart3, perm: "dashboard:viewTeam" },
  { href: "/reports/monthly", label: "Monthly Report", icon: FileBarChart, perm: "dashboard:viewTeam" },
  { href: "/appraisals", label: "Appraisals", icon: ClipboardCheck, perm: "appraisals:read" },
  { href: "/users", label: "Users", icon: Users, perm: "users:manage" },
  { href: "/settings", label: "Settings", icon: Settings, perm: "system:settings" },
];

export function AppShell({
  user,
  children,
}: {
  user: { name: string; email: string; role: Role; position: string | null };
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const [open, setOpen] = React.useState(false);

  const items = NAV.filter((n) => !n.perm || can(user.role, n.perm));

  return (
    <div className="flex h-screen overflow-hidden print:block print:h-auto print:overflow-visible">
      {/* Sidebar */}
      <aside
        className={cn(
          "no-print fixed inset-y-0 left-0 z-40 flex w-60 flex-col bg-sidebar text-sidebar-foreground transition-transform md:static md:translate-x-0",
          open ? "translate-x-0" : "-translate-x-full"
        )}
      >
        <div className="flex flex-col gap-2 px-5 py-4">
          <div className="flex items-center gap-3">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src="/logos/optimum-swim.png"
              alt="Optimum Swim School"
              className="h-9 w-auto"
            />
            <div className="h-7 w-px bg-white/15" />
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src="/logos/optimum-fit-white.png"
              alt="Optimum Fit"
              className="h-5 w-auto"
            />
          </div>
          <div className="text-[11px] font-semibold uppercase tracking-wide text-white/60">
            Marketing KPI
          </div>
        </div>

        <nav className="flex-1 space-y-1 overflow-y-auto px-3 py-2">
          {items.map((n) => {
            const active = pathname === n.href || pathname.startsWith(n.href + "/");
            const Icon = n.icon;
            return (
              <Link
                key={n.href}
                href={n.href}
                onClick={() => setOpen(false)}
                className={cn(
                  "flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors",
                  active
                    ? "bg-primary text-primary-foreground"
                    : "hover:bg-sidebar-accent hover:text-white"
                )}
              >
                <Icon className="size-4 shrink-0" />
                {n.label}
              </Link>
            );
          })}
        </nav>

        <div className="border-t border-white/10 p-3">
          <div className="mb-2 flex items-center gap-2 px-2">
            <div className="flex size-8 items-center justify-center rounded-full bg-primary text-xs font-bold text-primary-foreground">
              {initials(user.name)}
            </div>
            <div className="min-w-0 flex-1">
              <div className="truncate text-sm font-medium text-white">{user.name}</div>
              <div className="truncate text-[11px] opacity-70">
                {ROLE_LABELS[user.role]}
                {user.position ? ` · ${user.position}` : ""}
              </div>
            </div>
          </div>
          <div className="flex items-center justify-between">
            <ThemeToggle />
            <button
              onClick={() => signOut({ callbackUrl: "/login" })}
              className="flex items-center gap-2 rounded-md px-2 py-1.5 text-xs text-sidebar-foreground hover:bg-sidebar-accent"
            >
              <LogOut className="size-4" /> Sign out
            </button>
          </div>
        </div>
      </aside>

      {open && (
        <div
          className="fixed inset-0 z-30 bg-black/40 md:hidden"
          onClick={() => setOpen(false)}
        />
      )}

      {/* Main */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="no-print flex h-14 items-center gap-3 border-b border-border bg-card px-4 md:hidden">
          <button onClick={() => setOpen(true)} aria-label="Open menu">
            <Menu className="size-5" />
          </button>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src="/logos/optimum-swim.png"
            alt="Optimum Swim School"
            className="h-7 w-auto"
          />
          <span className="font-semibold">Marketing KPI</span>
        </header>
        <main className="flex-1 overflow-y-auto p-4 md:p-6 print:overflow-visible print:p-0">{children}</main>
      </div>
    </div>
  );
}
