import type { Subscription } from "@customer-portal/domain/subscriptions";
import {
  HomeIcon,
  CreditCardIcon,
  ServerIcon,
  ChatBubbleLeftRightIcon,
  UserIcon,
  ArrowRightStartOnRectangleIcon,
  Squares2X2Icon,
  ClipboardDocumentListIcon,
} from "@heroicons/react/24/outline";

export interface NavigationChild {
  name: string;
  href: string;
  icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  tooltip?: string;
}

export interface NavigationItem {
  name: string;
  href?: string;
  icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  children?: NavigationChild[];
  isLogout?: boolean;
}

export const baseNavigation: NavigationItem[] = [
  { name: "Dashboard", href: "/dashboard", icon: HomeIcon },
  { name: "Orders", href: "/orders", icon: ClipboardDocumentListIcon },
  {
    name: "Billing",
    icon: CreditCardIcon,
    children: [
      { name: "Invoices", href: "/billing/invoices" },
      { name: "Payment Methods", href: "/billing/payments" },
    ],
  },
  {
    name: "Subscriptions",
    icon: ServerIcon,
    children: [{ name: "All Subscriptions", href: "/subscriptions" }],
  },
  { name: "Catalog", href: "/catalog", icon: Squares2X2Icon },
  {
    name: "Support",
    icon: ChatBubbleLeftRightIcon,
    children: [
      { name: "Cases", href: "/support/cases" },
      { name: "New Case", href: "/support/new" },
      { name: "Knowledge Base", href: "/support/kb" },
    ],
  },
  {
    name: "Account",
    href: "/account",
    icon: UserIcon,
  },
  { name: "Log out", href: "#", icon: ArrowRightStartOnRectangleIcon, isLogout: true },
];

export function computeNavigation(activeSubscriptions?: Subscription[]): NavigationItem[] {
  const nav: NavigationItem[] = baseNavigation.map(item => ({
    ...item,
    children: item.children ? [...item.children] : undefined,
  }));

  const subIdx = nav.findIndex(n => n.name === "Subscriptions");
  if (subIdx >= 0) {
    const dynamicChildren = (activeSubscriptions || []).map(sub => ({
      name: truncate(sub.productName || `Subscription ${sub.id}`, 28),
      href: `/subscriptions/${sub.id}`,
      tooltip: sub.productName || `Subscription ${sub.id}`,
    }));

    nav[subIdx] = {
      ...nav[subIdx],
      children: [{ name: "All Subscriptions", href: "/subscriptions" }, ...dynamicChildren],
    };
  }

  return nav;
}

export function truncate(text: string, max: number): string {
  if (text.length <= max) return text;
  return text.slice(0, Math.max(0, max - 1)) + "…";
}
