"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { api } from "@/lib/api";
import { readBrand, writeBrand, applyBrandVars, DEFAULT_BRAND, type Brand } from "@/lib/brand";
import {
  LayoutDashboard,
  Users,
  Percent,
  Boxes,
  Layers,
  Ticket,
  Wallet,
  ShieldAlert,
  Settings,
  Receipt,
  Trophy,
  Megaphone,
  Image as ImageIcon,
  PanelLeftClose,
  PanelLeftOpen,
  Menu,
  X,
  ExternalLink,
} from "lucide-react";
import { cn } from "./cn";

const NAV = [
  { href: "/admin", label: "Overview", icon: LayoutDashboard, exact: true },
  { href: "/admin/affiliates", label: "Affiliates", icon: Users },
  { href: "/admin/campaigns", label: "Campaigns", icon: Layers },
  { href: "/admin/sales", label: "Sales", icon: Receipt },
  { href: "/admin/commission-groups", label: "Commission Groups", icon: Percent },
  { href: "/admin/product-commissions", label: "Product Commissions", icon: Boxes },
  { href: "/admin/coupons", label: "Coupons", icon: Ticket },
  { href: "/admin/payouts", label: "Payouts", icon: Wallet },
  { href: "/admin/leaderboard", label: "Leaderboard", icon: Trophy },
  { href: "/admin/marketing", label: "Marketing", icon: Megaphone },
  { href: "/admin/digital-assets", label: "Digital Assets", icon: ImageIcon },
  { href: "/admin/fraud", label: "Fraud", icon: ShieldAlert },
  { href: "/admin/settings", label: "Settings", icon: Settings },
];

export function AdminShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [collapsed, setCollapsed] = useState(false);
  const [drawer, setDrawer] = useState(false);
  const [demo, setDemo] = useState(false);
  useEffect(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      setDemo(p.get("demo") === "1" || sessionStorage.getItem("tk_demo") === "1");
    } catch {
      /* ignore */
    }
  }, []);
  const [brand, setBrand] = useState<Brand>(DEFAULT_BRAND);

  useEffect(() => {
    const cached = readBrand();
    if (cached.name || cached.logoUrl) setBrand(cached);
    applyBrandVars(cached);
    Promise.all([api.get("/admin/branding").catch(() => null), api.get("/admin/settings").catch(() => null)]).then(([b, s]) => {
      const next: Brand = { logoUrl: b?.logoUrl ?? null, name: s?.programName || "", brandColor: b?.brandColor ?? null, brandSecondaryColor: b?.brandSecondaryColor ?? null };
      setBrand(next);
      writeBrand(next);
      applyBrandVars(next);
    });
  }, []);

  const active = (href: string, exact?: boolean) =>
    exact ? pathname === href : pathname === href || pathname.startsWith(href + "/");

  const NavLinks = ({ collapsed }: { collapsed: boolean }) => (
    <nav className="flex-1 space-y-1 px-2 py-3">
      {NAV.map(({ href, label, icon: Icon, exact }) => {
        const on = active(href, exact);
        return (
          <Link
            key={href}
            href={href}
            title={collapsed ? label : undefined}
            onClick={() => setDrawer(false)}
            className={cn(
              "flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
              on ? "bg-[var(--brand)] text-white shadow-sm" : "text-gray-600 hover:bg-gray-100",
              collapsed && "justify-center px-0",
            )}
          >
            <Icon className={cn("h-[18px] w-[18px] shrink-0", on ? "text-white" : "text-gray-400")} />
            {!collapsed && <span className="truncate">{label}</span>}
          </Link>
        );
      })}
    </nav>
  );

  const Brand = ({ collapsed }: { collapsed: boolean }) => (
    <div className={cn("flex h-14 items-center gap-2 border-b border-gray-100 px-4", collapsed && "justify-center px-0")}>
      {brand.logoUrl ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={brand.logoUrl} alt={brand.name} className="h-8 w-8 shrink-0 rounded-lg object-contain" />
      ) : (
        <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--brand)] text-sm font-bold text-white">
          {brand.name.slice(0, 2).toUpperCase()}
        </span>
      )}
      {!collapsed && <span className="truncate text-sm font-bold tracking-tight text-gray-900">{brand.name}</span>}
    </div>
  );

  return (
    <div className="fixed inset-0 flex bg-[var(--background)]">
      {/* Desktop sidebar */}
      <aside
        className={cn(
          "hidden shrink-0 flex-col border-r border-gray-200 bg-white transition-[width] duration-200 lg:flex",
          collapsed ? "w-16" : "w-60",
        )}
      >
        <Brand collapsed={collapsed} />
        <NavLinks collapsed={collapsed} />
        <div className="border-t border-gray-100 p-2">
          <button
            onClick={() => setCollapsed((c) => !c)}
            className={cn(
              "flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-gray-500 hover:bg-gray-100",
              collapsed && "justify-center px-0",
            )}
          >
            {collapsed ? <PanelLeftOpen className="h-[18px] w-[18px]" /> : <PanelLeftClose className="h-[18px] w-[18px]" />}
            {!collapsed && <span>Collapse</span>}
          </button>
        </div>
      </aside>

      {/* Mobile drawer */}
      {drawer && (
        <div className="lg:hidden">
          <div className="pn-fade-in fixed inset-0 z-40 bg-slate-900/40" onClick={() => setDrawer(false)} />
          <aside className="fixed inset-y-0 left-0 z-50 flex w-64 flex-col border-r border-gray-200 bg-white">
            <div className="flex items-center justify-between pr-2">
              <Brand collapsed={false} />
              <button onClick={() => setDrawer(false)} className="text-gray-400 hover:text-gray-600">
                <X className="h-5 w-5" />
              </button>
            </div>
            <NavLinks collapsed={false} />
          </aside>
        </div>
      )}

      {/* Main column */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex h-14 shrink-0 items-center justify-between border-b border-gray-200 bg-white px-4 sm:px-6">
          <div className="flex items-center gap-3">
            <button onClick={() => setDrawer(true)} className="text-gray-500 hover:text-gray-700 lg:hidden">
              <Menu className="h-5 w-5" />
            </button>
            <span className="text-sm font-semibold text-gray-500">Admin</span>
          </div>
          <Link
            href="/store"
            className="inline-flex items-center gap-1.5 rounded-lg border border-gray-300 px-3 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50"
          >
            <ExternalLink className="h-3.5 w-3.5" /> View demo store
          </Link>
        </header>
        {demo && (
          <div className="flex shrink-0 items-center justify-center gap-2 bg-[var(--brand)] px-4 py-2 text-center text-xs font-medium text-white">
            <span>You&rsquo;re viewing a live demo with sample data — changes are disabled.</span>
            <a href="https://apps.shopify.com/" className="rounded-md bg-white/20 px-2.5 py-1 font-semibold ring-1 ring-inset ring-white/30 hover:bg-white/30">
              Add to Shopify
            </a>
          </div>
        )}
        <main className="flex-1 overflow-y-auto p-4 sm:p-6 lg:px-8">
          <div className="mx-auto max-w-[1600px]">{children}</div>
        </main>
      </div>
    </div>
  );
}
