"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import {
  BarChart3,
  Bell,
  Building2,
  CalendarClock,
  ClipboardList,
  CreditCard,
  FileSpreadsheet,
  Files,
  FolderKanban,
  HandCoins,
  HardHat,
  Home,
  LogOut,
  Menu,
  PanelLeftClose,
  PanelLeftOpen,
  Receipt,
  Settings,
  ShieldCheck,
  Users,
  WalletCards,
  X
} from "lucide-react";
import { logoutAction } from "@/app/actions";
import type { PermissionMap, PermissionKey } from "@/lib/permissions";
import type { getProjectsForUser } from "@/lib/projects";
import { ProjectSelector } from "./ProjectSelector";

const roleLabels: Record<string, string> = {
  OWNER: "Owner",
  ADMIN: "Admin",
  EDITOR: "Editor",
  CONTRIBUTOR: "Contributor",
  VIEWER: "Viewer",
  RECEIPT_UPLOADER: "Receipt Uploader",
  TENANT: "Tenant",
  CUSTOM: "Custom"
};

type BrandingState = {
  appName: string;
  headerTitle?: string | null;
  logoUrl?: string | null;
  smallLogoUrl?: string | null;
  faviconUrl?: string | null;
  showProjectName: boolean;
  showSidebarLogo: boolean;
  showHeaderLogo: boolean;
};

const navItems = [
  { href: "/", label: "Dashboard", icon: Home, permission: "dashboard.view" },
  { href: "/projects", label: "Projects", icon: FolderKanban, permission: "project.view" },
  { href: "/partners", label: "Partners", icon: Users, permission: "partners.view" },
  { href: "/contributions", label: "Contributions", icon: HandCoins, permission: "contributions.view" },
  { href: "/purchase-costs", label: "Purchase Costs", icon: Receipt, permission: "purchaseCosts.view" },
  { href: "/renovation-costs", label: "Renovation Costs", icon: Building2, permission: "renovationCosts.view" },
  { href: "/workers", label: "Workers", icon: HardHat, permission: "expenses.view" },
  { href: "/operating-expenses", label: "Operating Expenses", icon: CreditCard, permission: "operatingExpenses.view" },
  { href: "/transactions", label: "All Transactions", icon: FileSpreadsheet, permission: "reports.view" },
  { href: "/tenants", label: "Tenants & Units", icon: Users, permission: "tenants.view" },
  { href: "/rent", label: "Rent Payments", icon: WalletCards, permission: "rentPayments.view" },
  { href: "/security-deposits", label: "Security Deposits", icon: ShieldCheck, permission: "securityDeposits.view" },
  { href: "/recurring-bills", label: "Recurring Bills", icon: CalendarClock, permission: "recurringBills.view" },
  { href: "/documents", label: "Documents", icon: Files, permission: "documents.view" },
  { href: "/profit-loss", label: "Profit/Loss", icon: BarChart3, permission: "profitLoss.view" },
  { href: "/settlements", label: "Partner Settlement", icon: HandCoins, permission: "settlement.view" },
  { href: "/reports", label: "Reports", icon: ClipboardList, permission: "reports.view" },
  { href: "/import", label: "Import", icon: FileSpreadsheet, permission: "expenses.create" },
  { href: "/review-records", label: "Review Records", icon: ClipboardList, permission: "expenses.edit" },
  { href: "/review-funding-sources", label: "Review Funding", icon: WalletCards, permission: "expenses.edit" },
  { href: "/settings/branding", label: "Branding", icon: Settings, permission: "settings.edit" },
  { href: "/settings/categories", label: "Settings / Categories", icon: Settings, permission: "categories.view" },
  { href: "/settings/users", label: "Users & Permissions", icon: ShieldCheck, permission: "users.view" }
];

export function AppShell({
  children,
  projects,
  selectedProjectId,
  username,
  role,
  permissions
}: {
  children: React.ReactNode;
  projects: Awaited<ReturnType<typeof getProjectsForUser>>;
  selectedProjectId?: string;
  username?: string | null;
  role: string;
  permissions?: PermissionMap | null;
}) {
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const pathname = usePathname();
  const [branding, setBranding] = useState<BrandingState>({
    appName: "Partnership Tracker",
    headerTitle: null,
    logoUrl: null,
    smallLogoUrl: null,
    faviconUrl: null,
    showProjectName: true,
    showSidebarLogo: true,
    showHeaderLogo: false
  });
  const projectQuery = selectedProjectId ? `?projectId=${selectedProjectId}` : "";
  const projectOptions = projects.map((project) => ({ id: project.id, name: project.name }));
  const selectedProjectName = projectOptions.find((project) => project.id === selectedProjectId)?.name ?? projectOptions[0]?.name ?? "Partnership Tracker";
  const visibleNavItems = permissions
    ? navItems.filter((item) => permissions[item.permission as PermissionKey])
    : navItems;
  const displayRole = roleLabels[role as keyof typeof roleLabels] ?? role;

  useEffect(() => {
    let active = true;
    fetch("/api/branding", { cache: "no-store" })
      .then((response) => response.json())
      .then((nextBranding) => {
        if (!active) return;
        setBranding(nextBranding);
        if (nextBranding.faviconUrl) {
          let link = document.querySelector<HTMLLinkElement>('link[rel="icon"]');
          if (!link) {
            link = document.createElement("link");
            link.rel = "icon";
            document.head.appendChild(link);
          }
          link.href = nextBranding.faviconUrl;
        }
        document.title = nextBranding.headerTitle || nextBranding.appName || "Partnership Tracker";
      })
      .catch(() => {});
    return () => {
      active = false;
    };
  }, []);

  return (
    <div className="min-h-screen bg-canvas">
      {mobileOpen ? (
        <button className="fixed inset-0 z-30 bg-slate-950/40 lg:hidden" type="button" aria-label="Close navigation" onClick={() => setMobileOpen(false)} />
      ) : null}
      <aside className={`fixed inset-y-0 left-0 z-40 border-r border-line bg-white transition-all duration-200 lg:block ${mobileOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"} ${collapsed ? "w-20" : "w-72 lg:w-64"}`}>
        <div className={`flex h-16 items-center gap-3 border-b border-line px-4 ${collapsed ? "justify-center" : "justify-between"}`}>
          <Link href={`/${projectQuery}`} className={`min-w-0 ${collapsed ? "sr-only" : "flex items-center gap-3"}`}>
            {branding.showSidebarLogo && (branding.logoUrl || branding.smallLogoUrl) ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img className="h-10 w-10 rounded-md object-contain" src={branding.smallLogoUrl ?? branding.logoUrl ?? ""} alt="" />
            ) : (
              <span className="grid h-10 w-10 place-items-center rounded-md bg-blue-600 text-sm font-semibold text-white">NN</span>
            )}
            <span className="min-w-0">
              <span className="block text-xs font-semibold uppercase tracking-normal text-blue-700">Workspace</span>
              <span className="mt-1 block truncate text-base font-semibold text-ink">{branding.appName || "Partnership Tracker"}</span>
            </span>
          </Link>
          <div className="flex items-center gap-2">
            <button className="btn-secondary hidden px-2 py-1 lg:inline-flex" type="button" onClick={() => setCollapsed((value) => !value)} title={collapsed ? "Expand sidebar" : "Collapse sidebar"}>
              {collapsed ? <PanelLeftOpen className="h-4 w-4" aria-hidden="true" /> : <PanelLeftClose className="h-4 w-4" aria-hidden="true" />}
              <span className="sr-only">{collapsed ? "Expand sidebar" : "Collapse sidebar"}</span>
            </button>
            <button className="btn-secondary px-2 py-1 lg:hidden" type="button" onClick={() => setMobileOpen(false)} title="Close menu">
              <X className="h-4 w-4" aria-hidden="true" />
              <span className="sr-only">Close menu</span>
            </button>
          </div>
        </div>
        <nav className="flex max-h-[calc(100vh-64px)] flex-col gap-1 overflow-y-auto px-3 py-4">
          {visibleNavItems.map((item) => {
            const Icon = item.icon;
            const active = pathname === item.href || (item.href !== "/" && pathname?.startsWith(item.href));
            return (
              <Link
                key={item.href}
                href={`${item.href}${projectQuery}`}
                onClick={() => setMobileOpen(false)}
                className={`flex items-center gap-3 rounded-md px-3 py-2 text-sm font-semibold transition ${active ? "bg-blue-50 text-blue-700" : "text-slate-600 hover:bg-slate-100 hover:text-ink"} ${collapsed ? "justify-center" : ""}`}
                aria-current={active ? "page" : undefined}
                title={item.label}
              >
                <Icon className="h-4 w-4 shrink-0" aria-hidden="true" />
                <span className={collapsed ? "sr-only" : ""}>{item.label}</span>
              </Link>
            );
          })}
        </nav>
      </aside>

      <div className={`transition-all duration-200 ${collapsed ? "lg:pl-20" : "lg:pl-64"}`}>
        <header className="sticky top-0 z-20 border-b border-line bg-white/95 px-4 py-3 backdrop-blur lg:px-8">
          <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <div className="flex min-w-0 items-center gap-3">
              <button className="btn-secondary px-2 py-1 lg:hidden" type="button" onClick={() => setMobileOpen(true)} title="Open menu">
                <Menu className="h-4 w-4" aria-hidden="true" />
                <span className="sr-only">Open menu</span>
              </button>
              {branding.showHeaderLogo && (branding.smallLogoUrl || branding.logoUrl) ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img className="h-9 w-9 rounded-md object-contain" src={branding.smallLogoUrl ?? branding.logoUrl ?? ""} alt="" />
              ) : null}
              <div className="min-w-0">
                <p className="text-xs font-semibold uppercase tracking-normal text-blue-700">Current Project</p>
                <p className="truncate text-sm font-semibold text-ink md:text-base">
                  {branding.showProjectName ? selectedProjectName : (branding.headerTitle || branding.appName || "Partnership Tracker")}
                </p>
              </div>
            </div>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end">
              <ProjectSelector projects={projectOptions} selectedProjectId={selectedProjectId} />
              <button className="btn-secondary self-start sm:self-auto" type="button" title="Recurring bill notifications">
                <Bell className="h-4 w-4" aria-hidden="true" />
                <span className="sr-only">Notifications</span>
              </button>
              <div className="text-left text-sm sm:text-right">
                <p className="font-medium text-ink">{username ?? "User"}</p>
                <p className="mt-1 inline-flex rounded-md border border-line bg-slate-50 px-2 py-0.5 text-xs font-semibold uppercase tracking-normal text-slate-600">{displayRole}</p>
              </div>
              <form action={logoutAction}>
                <button className="btn-secondary" title="Sign out">
                  <LogOut className="h-4 w-4" aria-hidden="true" />
                  <span className="sr-only">Sign out</span>
                </button>
              </form>
            </div>
          </div>
        </header>
        <main className="mx-auto w-full max-w-[1600px] px-4 py-6 lg:px-8">{children}</main>
      </div>
    </div>
  );
}
