import { useState } from "react";
import { NavLink, useLocation } from "react-router-dom";
import { useAuth } from "../auth/AuthContext";

// Icons
import DashboardIcon from "../assets/side-menu-icons/dashboard.svg?react";
import MelodiesIcon from "../assets/side-menu-icons/melodies.svg?react";
import MelodiesEditorIcon from "../assets/side-menu-icons/melodies-editor.svg?react";
import ArchetypesIcon from "../assets/side-menu-icons/archetypes.svg?react";
import MelodySettingsIcon from "../assets/side-menu-icons/melody-settings.svg?react";
import ComposerIcon from "../assets/side-menu-icons/composer.svg?react";
import DevicesIcon from "../assets/side-menu-icons/devices.svg?react";
import DeviceOverviewIcon from "../assets/side-menu-icons/device-overview.svg?react";
import FleetIcon from "../assets/side-menu-icons/fleet.svg?react";
import BlackBoxIcon from "../assets/side-menu-icons/blackbox.svg?react";
import AppUsersIcon from "../assets/side-menu-icons/app-users.svg?react";
import MqttCommandsIcon from "../assets/side-menu-icons/mqtt-commands.svg?react";
import MailIcon from "../assets/side-menu-icons/mail.svg?react";
import CommunicationsIcon from "../assets/side-menu-icons/communications.svg?react";
import WhatsAppIcon from "../assets/side-menu-icons/whatsapp.svg?react";
import SmsIcon from "../assets/side-menu-icons/sms.svg?react";
import HelpdeskIcon from "../assets/side-menu-icons/helpdesk.svg?react";
import CommsLogIcon from "../assets/side-menu-icons/communications-log.svg?react";
import CustomersIcon from "../assets/side-menu-icons/customers.svg?react";
import OrdersIcon from "../assets/side-menu-icons/orders.svg?react";
import QuotationsIcon from "../assets/side-menu-icons/quotations.svg?react";
import ProductsIcon from "../assets/side-menu-icons/products.svg?react";
import StaffNotesIcon from "../assets/side-menu-icons/staff-notes.svg?react";
import ManufacturingIcon from "../assets/side-menu-icons/manufacturing.svg?react";
import DeviceInventoryIcon from "../assets/side-menu-icons/device-inventory.svg?react";
import ProvisionIcon from "../assets/side-menu-icons/provision.svg?react";
import FirmwareIcon from "../assets/side-menu-icons/firmware.svg?react";
import ApiIcon from "../assets/side-menu-icons/api.svg?react";
import SettingsIcon from "../assets/side-menu-icons/settings.svg?react";
import StaffIcon from "../assets/side-menu-icons/staff.svg?react";
import CustomerOverviewIcon from "../assets/side-menu-icons/customer-overview.svg?react";
import ProductCatalogIcon from "../assets/side-menu-icons/product-catalog.svg?react";
import SnManagerIcon from "../assets/side-menu-icons/sn-manager.svg?react";

// Placeholder icon for items without a dedicated SVG yet
function PlaceholderIcon({ className }) {
  return (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <rect x="3" y="3" width="18" height="18" rx="3" strokeWidth={1.8} />
      <path d="M9 9l6 6M15 9l-6 6" strokeWidth={1.8} strokeLinecap="round" />
    </svg>
  );
}

// ─── Nav structure ────────────────────────────────────────────────────────────
// Each top-level entry is one of:
//   { type: "separator", label }  → section header
//   { to, label, icon, permission? }  → single link
//   { label, icon, permission?, children[] }  → collapsible group

const navSections = [
  // ── General ───────────────────────────────────────────────────────────────
  { type: "separator", label: "General" },
  { to: "/", label: "Dashboard", icon: DashboardIcon, permission: null },

  // ── Bell Cloud ────────────────────────────────────────────────────────────
  { type: "separator", label: "Bell Cloud" },

  {
    label: "Devices",
    icon: DevicesIcon,
    permission: "devices",
    children: [
      { to: "/devices/overview",  label: "Overview",        icon: DeviceOverviewIcon, placeholder: true },
      { to: "/devices",           label: "Fleet",           icon: FleetIcon,          exact: true },
      { to: "/mqtt/commands",     label: "Command Center",  icon: MqttCommandsIcon },
      { to: "/equipment/notes",   label: "BlackBox",        icon: BlackBoxIcon },
      { to: "/devices/settings",  label: "Device Settings", icon: PlaceholderIcon,    placeholder: true },
    ],
  },

  { to: "/users", label: "Users", icon: AppUsersIcon, permission: "app_users" },

  {
    label: "Melodies",
    icon: MelodiesIcon,
    permission: "melodies",
    children: [
      { to: "/melodies",            label: "Library",         icon: MelodiesEditorIcon, exact: true },
      { to: "/melodies/composer",   label: "Composer",        icon: ComposerIcon },
      { to: "/melodies/archetypes", label: "Archetypes",      icon: ArchetypesIcon },
      { to: "/melodies/settings",   label: "Melody Settings", icon: MelodySettingsIcon },
    ],
  },

  // ── Headquarters ────────────────────────────────────────────────────
  { type: "separator", label: "Headquarters" },

  {
    label: "Communications",
    icon: CommunicationsIcon,
    permission: "crm",
    children: [
      { to: "/mail",           label: "Mailbox",   icon: MailIcon },
      { to: "/comms/whatsapp", label: "WhatsApp",  icon: WhatsAppIcon,  placeholder: true },
      { to: "/comms/sms",      label: "SMS",       icon: SmsIcon,       placeholder: true },
      { to: "/comms/helpdesk", label: "Helpdesk",  icon: HelpdeskIcon,  placeholder: true },
      { to: "/crm/comms",      label: "Comms Log", icon: CommsLogIcon },
    ],
  },

  {
    label: "Customers",
    icon: CustomersIcon,
    permission: "crm",
    children: [
      { to: "/crm/customers",  label: "Overview",  icon: CustomerOverviewIcon},
      { to: "/crm/orders",     label: "Orders",     icon: OrdersIcon },
      { to: "/crm/quotations", label: "Quotations", icon: QuotationsIcon },
    ],
  },

  {
    label: "Products",
    icon: ProductsIcon,
    permission: "crm",
    children: [
      { to: "/crm/products",    label: "Catalog",     icon: ProductCatalogIcon },
      { to: "/crm/products/sn", label: "S/N Manager", icon: SnManagerIcon, placeholder: true },
    ],
  },
  { to: "/staff-log",    label: "Staff Log", icon: StaffNotesIcon, permission: null, placeholder: true },

  // ── Engineering ───────────────────────────────────────────────────────────
  { type: "separator", label: "Engineering" },

  {
    label: "Manufacturing",
    icon: ManufacturingIcon,
    permission: "manufacturing",
    children: [
      { to: "/manufacturing",           label: "Inventory",    icon: DeviceInventoryIcon, exact: true },
      { to: "/manufacturing/provision", label: "Provisioning", icon: ProvisionIcon },
    ],
  },

  { to: "/firmware",      label: "Firmware Manager", icon: FirmwareIcon, permission: "manufacturing" },
  { to: "/developer/api", label: "API Reference",    icon: ApiIcon,      permission: null, roleRequired: ["sysadmin", "admin"] },
];

// Bottom settings — always rendered separately at the bottom
const settingsChildren = [
  { to: "/settings/staff",            label: "Staff Management", icon: StaffIcon },
  { to: "/settings/public-features",  label: "Public Features",  icon: SettingsIcon },
  { to: "/settings/serial-logs",      label: "Log Viewer",       icon: BlackBoxIcon },
  { to: "/settings/pages",            label: "Page Settings",    icon: PlaceholderIcon, placeholder: true },
];

// ─── Helpers ──────────────────────────────────────────────────────────────────
const iconClass = "w-4 h-4 flex-shrink-0";

function isGroupActive(children, pathname) {
  return children.some((child) => {
    if (child.exact) return pathname === child.to;
    return pathname === child.to || pathname.startsWith(child.to + "/");
  });
}

const linkClass = (isActive, locked) =>
  `block px-3 py-2 rounded-md text-sm transition-colors ${
    locked
      ? "opacity-40 cursor-not-allowed"
      : isActive
        ? "bg-[var(--accent)] text-[var(--bg-primary)] font-medium"
        : "text-[var(--text-secondary)] hover:bg-[var(--bg-card-hover)] hover:text-[var(--text-heading)]"
  }`;

// ─── Section separator ────────────────────────────────────────────────────────
function SectionSeparator({ label, first = false }) {
  return (
    <div className={`flex items-center gap-2 px-1 ${first ? "pt-3" : "pt-6"} pb-1.5`}>
      <span
        className="text-[10px] font-bold uppercase tracking-widest whitespace-nowrap flex-shrink-0"
        style={{ color: "var(--text-muted)", letterSpacing: "0.08em" }}
      >
        {label}
      </span>
      <div className="h-px flex-1 opacity-30" style={{ backgroundColor: "var(--border-primary)" }} />
    </div>
  );
}

// ─── Collapsible group ────────────────────────────────────────────────────────
function CollapsibleGroup({ label, icon: Icon, children, currentPath, locked = false, open, onToggle }) {
  const childActive = isGroupActive(children, currentPath);
  const shouldBeOpen = open || childActive;

  return (
    <div className="mb-0.5">
      <button
        type="button"
        onClick={() => !locked && onToggle()}
        className={`w-full flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors ${
          locked
            ? "opacity-40 cursor-not-allowed"
            : childActive
              ? "text-[var(--text-heading)] font-medium"
              : "text-[var(--text-secondary)] hover:bg-[var(--bg-card-hover)] hover:text-[var(--text-heading)]"
        }`}
      >
        <span className="flex items-center gap-2">
          {Icon && <Icon className="w-4 h-4 flex-shrink-0" />}
          {label}
          {locked && (
            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          )}
        </span>
        {!locked && (
          <svg
            className={`w-3.5 h-3.5 transition-transform flex-shrink-0 ${shouldBeOpen ? "rotate-90" : ""}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        )}
      </button>

      {!locked && shouldBeOpen && (
        <div className="ml-3 mt-0.5 space-y-0.5 border-l" style={{ borderColor: "var(--border-primary)", borderLeftStyle: "solid" }}>
          {children.map((child) =>
            child.placeholder ? (
              <div
                key={child.to}
                className="flex items-center gap-2 pl-4 pr-3 py-1.5 rounded-r-md text-sm opacity-40 cursor-not-allowed select-none"
                style={{ color: "var(--text-muted)" }}
              >
                {child.icon && <child.icon className="w-3.5 h-3.5 flex-shrink-0" />}
                <span>{child.label}</span>
                <span
                  className="ml-auto text-[9px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded"
                  style={{ background: "var(--border-primary)", color: "var(--text-muted)" }}
                >
                  soon
                </span>
              </div>
            ) : (
              <NavLink
                key={child.to}
                to={child.to}
                end={child.exact === true}
                className={({ isActive }) =>
                  `flex items-center gap-2 pl-4 pr-3 py-1.5 rounded-r-md text-sm transition-colors ${
                    isActive
                      ? "bg-[var(--accent)] text-[var(--bg-primary)] font-medium"
                      : "text-[var(--text-muted)] hover:bg-[var(--bg-card-hover)] hover:text-[var(--text-heading)]"
                  }`
                }
              >
                {child.icon && <child.icon className="w-3.5 h-3.5 flex-shrink-0" />}
                <span>{child.label}</span>
              </NavLink>
            )
          )}
        </div>
      )}
    </div>
  );
}

// ─── Main Sidebar ─────────────────────────────────────────────────────────────
export default function Sidebar() {
  const { hasPermission, hasRole } = useAuth();
  const location = useLocation();

  const [openGroup, setOpenGroup] = useState(() => {
    for (const item of navSections) {
      if (item.children && isGroupActive(item.children, location.pathname)) {
        return item.label;
      }
    }
    if (isGroupActive(settingsChildren, location.pathname)) return "Console Settings";
    return null;
  });

  const canView = (item) => {
    if (item.roleRequired) return hasRole(...item.roleRequired);
    if (!item.permission) return true;
    return hasPermission(item.permission, "view");
  };

  const canManageStaff = hasRole("sysadmin", "admin");

  const handleGroupToggle = (label) => {
    setOpenGroup((prev) => (prev === label ? null : label));
  };

  return (
    <aside
      className="w-56 flex-shrink-0 flex flex-col overflow-y-auto"
      style={{ backgroundColor: "var(--bg-sidebar)", borderRight: "1px solid var(--border-primary)" }}
    >
      <nav className="flex-1 px-3 py-3 space-y-0.5">
        {navSections.map((item, idx) => {
          // Section separator
          if (item.type === "separator") {
            return <SectionSeparator key={`sep-${idx}`} label={item.label} first={idx === 0} />;
          }

          // Skip developer/API if no role
          if (!canView(item)) return null;

          // Placeholder items — render greyed out, non-navigable
          if (item.placeholder) {
            return (
              <div
                key={item.to}
                className="flex items-center gap-2 px-3 py-2 rounded-md text-sm opacity-40 cursor-not-allowed select-none"
                style={{ color: "var(--text-secondary)" }}
              >
                <item.icon className={iconClass} />
                {item.label}
                <span
                  className="ml-auto text-[9px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded"
                  style={{ background: "var(--border-primary)", color: "var(--text-muted)" }}
                >
                  soon
                </span>
              </div>
            );
          }

          // Collapsible group
          if (item.children) {
            const locked = !canView(item);
            return (
              <CollapsibleGroup
                key={item.label}
                label={item.label}
                icon={item.icon}
                children={item.children}
                currentPath={location.pathname}
                locked={locked}
                open={openGroup === item.label}
                onToggle={() => handleGroupToggle(item.label)}
              />
            );
          }

          // Single link
          const hasAccess = canView(item);
          return (
            <NavLink
              key={item.to}
              to={hasAccess ? item.to : "#"}
              end={item.to === "/"}
              className={({ isActive }) => linkClass(isActive && hasAccess, !hasAccess)}
              onClick={(e) => {
                if (!hasAccess) { e.preventDefault(); return; }
                setOpenGroup(null);
              }}
            >
              <span className="flex items-center gap-2">
                {item.icon && <item.icon className={iconClass} />}
                {item.label}
                {!hasAccess && (
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                  </svg>
                )}
              </span>
            </NavLink>
          );
        })}
      </nav>

      {/* ── Console Settings (bottom) ── */}
      {canManageStaff && (
        <div className="px-3 pb-3 border-t pt-3" style={{ borderColor: "var(--border-primary)" }}>
          <CollapsibleGroup
            label="Console Settings"
            icon={SettingsIcon}
            children={settingsChildren}
            currentPath={location.pathname}
            open={openGroup === "Console Settings"}
            onToggle={() => handleGroupToggle("Console Settings")}
          />
        </div>
      )}
    </aside>
  );
}
