"use client";

import Link from "next/link";
import { useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { brand } from "@/lib/brand";

export type NavigationGroup = {
  label: string;
  collapsible?: boolean;
  items: Array<{ label: string; href: string; icon: IconName }>;
};

type IconName = "dashboard" | "orders" | "products" | "stock" | "stores" | "finance" | "reports" | "optimizer" | "integrations" | "logs" | "users" | "settings";

function Icon({ name }: { name: IconName }) {
  const paths: Record<IconName, React.ReactNode> = {
    dashboard: <><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></>,
    orders: <><path d="M6 3h12l2 4H4l2-4Z"/><path d="M5 7v14h14V7"/><path d="M9 11h6"/></>,
    products: <><path d="m12 3 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 16 9 5 9-5"/></>,
    stock: <><path d="M4 7h16v14H4z"/><path d="M7 3h10l3 4H4l3-4Z"/><path d="M9 11h6"/></>,
    stores: <><path d="M3 10h18"/><path d="m5 10 1-6h12l1 6"/><path d="M5 10v11h14V10"/><path d="M9 21v-6h6v6"/></>,
    finance: <><circle cx="12" cy="12" r="9"/><path d="M16 8.5c-.8-.8-2-1.2-3.4-1.2-1.8 0-3.1.8-3.1 2.1 0 3.4 7 1.3 7 4.7 0 1.5-1.5 2.6-3.7 2.6-1.6 0-3-.5-4-1.5M12 5.5v13"/></>,
    reports: <><path d="M5 3h14v18H5z"/><path d="M8 15v3M12 11v7M16 8v10"/></>,
    optimizer: <><path d="M4 19V9M10 19V5M16 19v-7M22 19H2"/><path d="m4 7 5-4 6 6 6-5"/></>,
    integrations: <><path d="M8 12h8"/><path d="M10 8H7a4 4 0 0 0 0 8h3M14 8h3a4 4 0 0 1 0 8h-3"/></>,
    logs: <><path d="M5 4h14v16H5z"/><path d="M8 8h8M8 12h8M8 16h5"/></>,
    users: <><circle cx="9" cy="8" r="3"/><path d="M3 20c0-4 2.5-6 6-6s6 2 6 6"/><path d="M16 7a3 3 0 0 1 0 6M17 15c2.4.5 4 2.2 4 5"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1-2.8 2.8-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.6v.2h-4V21a1.7 1.7 0 0 0-1-1.6 1.7 1.7 0 0 0-1.9.3l-.1.1L4.2 17l.1-.1a1.7 1.7 0 0 0 .3-1.9A1.7 1.7 0 0 0 3 14H2.8v-4H3a1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9L4.2 7 7 4.2l.1.1a1.7 1.7 0 0 0 1.9.3A1.7 1.7 0 0 0 10 3V2.8h4V3a1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1L19.8 7l-.1.1a1.7 1.7 0 0 0-.3 1.9 1.7 1.7 0 0 0 1.6 1h.2v4H21a1.7 1.7 0 0 0-1.6 1Z"/></>,
  };
  return <svg aria-hidden="true" className="h-[18px] w-[18px]" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.7" viewBox="0 0 24 24">{paths[name]}</svg>;
}

function isActive(pathname: string, href: string, currentShopId: string) {
  const route = href.split("?")[0];
  if (route === "/dashboard") {
    const targetShopId = new URLSearchParams(href.split("?")[1] || "").get("shop_id");
    return (pathname === "/" || pathname === route) && (!targetShopId || targetShopId === currentShopId);
  }
  if (route === "/tokens") return ["/tokens", "/integrations"].some((path) => pathname === path || pathname.startsWith(`${path}/`));
  return pathname === route || pathname.startsWith(`${route}/`);
}

export default function Sidebar({
  groups,
  open,
  collapsed,
  mode = "workspace",
  onClose,
  onToggle,
}: {
  groups: NavigationGroup[];
  open: boolean;
  collapsed: boolean;
  mode?: "admin" | "workspace";
  onClose: () => void;
  onToggle: () => void;
}) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const currentShopId = searchParams.get("shop_id") || "all";
  const [expanded, setExpanded] = useState<{ path: string; values: Record<string, boolean> }>({ path: pathname, values: {} });
  const expandedValues = expanded.path === pathname ? expanded.values : {};
  return (
    <>
      {open ? <button aria-label="Tutup menu" className="fixed inset-0 z-50 bg-slate-950/45 backdrop-blur-sm lg:hidden" onClick={onClose} /> : null}
      <aside className={[
        "fixed inset-y-0 left-0 z-[60] flex w-[248px] flex-col border-r border-slate-200 bg-white text-slate-600 shadow-xl shadow-slate-950/5 transition-[width,transform] duration-200 dark:border-slate-800 dark:bg-[#0b1220] dark:text-slate-300 lg:sticky lg:top-0 lg:z-40 lg:h-dvh lg:translate-x-0",
        collapsed ? "lg:w-[78px]" : "lg:w-[248px]",
        open ? "translate-x-0" : "-translate-x-full",
      ].join(" ")}>
        <div className="flex h-16 items-center gap-3 border-b border-slate-200 px-4 dark:border-slate-800">
          <span className="grid h-9 w-9 shrink-0 place-items-center rounded-[10px] bg-emerald-500 text-[11px] font-black text-white shadow-sm">{brand.shortName}</span>
          {!collapsed ? <div className="min-w-0 flex-1"><div className="truncate text-[16px] font-bold tracking-tight text-slate-950 dark:text-white">Sellfin</div><div className="mt-0.5 truncate text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-400">{mode === "admin" ? "SaaS Administration" : "Shopee Operations"}</div></div> : null}
          <button aria-label={collapsed ? "Perluas sidebar" : "Ciutkan sidebar"} className="hidden h-8 w-8 shrink-0 place-items-center rounded-lg text-slate-400 hover:bg-slate-100 hover:text-slate-700 dark:hover:bg-slate-800 dark:hover:text-white lg:grid" onClick={onToggle} type="button">
            <svg className={`h-4 w-4 transition-transform ${collapsed ? "rotate-180" : ""}`} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></svg>
          </button>
        </div>

        <nav aria-label="Navigasi utama" className="flex-1 space-y-5 overflow-y-auto px-3 py-5">
          {groups.map((group) => {
            const groupActive = group.items.some((item) => isActive(pathname, item.href, currentShopId));
            const isExpanded = expandedValues[group.label] ?? groupActive;
            return <div key={group.label}>
              {group.collapsible ? <button aria-expanded={isExpanded} className={`flex w-full items-center rounded-[9px] px-3 py-2.5 text-[13px] font-bold text-slate-700 hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800 ${collapsed ? "justify-center px-0" : "gap-3"}`} onClick={() => { if (collapsed) onToggle(); setExpanded({ path: pathname, values: { ...expandedValues, [group.label]: !isExpanded || collapsed } }); }} title={collapsed ? group.label : undefined} type="button"><Icon name="settings" />{!collapsed ? <><span className="flex-1 text-left">{group.label}</span><span className={`text-slate-400 transition-transform ${isExpanded ? "rotate-180" : ""}`}>⌄</span></> : null}</button> : !collapsed ? <div className="mb-2 px-2.5 text-[10px] font-bold uppercase tracking-[0.14em] text-slate-400 dark:text-slate-600">{group.label}</div> : <div className="mx-auto mb-2 h-px w-6 bg-slate-200 dark:bg-slate-800" />}
              <div className={`space-y-0.5 ${group.collapsible ? `mt-1 border-l border-slate-200 pl-2 dark:border-slate-800 ${isExpanded ? "" : "hidden"} ${collapsed ? "lg:hidden" : ""}` : ""}`}>
                {group.items.map((item) => {
                  const selected = isActive(pathname, item.href, currentShopId);
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      title={collapsed ? item.label : undefined}
                      onClick={onClose}
                      className={[
                        "group relative flex h-10 items-center gap-3 rounded-[9px] px-3 text-[13px] font-semibold transition-colors",
                        collapsed ? "justify-center px-0" : "",
                        selected
                          ? "bg-emerald-50 text-emerald-800 ring-1 ring-inset ring-emerald-100 before:absolute before:inset-y-2 before:left-0 before:w-0.5 before:rounded-full before:bg-emerald-500 dark:bg-emerald-400/12 dark:text-emerald-300 dark:ring-emerald-400/10"
                          : "text-slate-600 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-400 dark:hover:bg-slate-800/80 dark:hover:text-white",
                      ].join(" ")}
                    >
                      <span className={selected ? "text-emerald-600 dark:text-emerald-300" : "text-slate-400 group-hover:text-slate-700 dark:text-slate-500 dark:group-hover:text-slate-200"}><Icon name={item.icon} /></span>
                      {!collapsed ? <span className="truncate">{item.label}</span> : null}
                      {!collapsed && selected ? <span className="ml-auto h-1.5 w-1.5 rounded-full bg-emerald-500" /> : null}
                    </Link>
                  );
                })}
              </div>
            </div>;
          })}
        </nav>

        <div className="border-t border-slate-200 p-3 dark:border-slate-800">
          <div className={`flex items-center rounded-[10px] bg-slate-50 px-3 py-2.5 dark:bg-slate-900 ${collapsed ? "justify-center px-0" : "gap-3"}`} title={mode === "admin" ? "Mode administrasi Sellfin" : "Shopee Live terhubung"}>
            <span className="relative flex h-2.5 w-2.5 shrink-0"><span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-30" /><span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-400" /></span>
            {!collapsed ? <div className="min-w-0"><div className="truncate text-[11px] font-bold text-slate-700 dark:text-slate-200">{mode === "admin" ? "Sellfin Admin" : "Shopee Live"}</div><div className="truncate text-[10px] text-slate-400">{mode === "admin" ? "Kontrol Owner & akses" : "sellfin.my.id"}</div></div> : null}
          </div>
        </div>
      </aside>
    </>
  );
}
