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>> | undefined;
  tooltip?: string | undefined;
}

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

export const baseNavigation: NavigationItem[] = [
  { name: "Dashboard", href: "/account", icon: HomeIcon },
  { name: "Orders", href: "/account/orders", icon: ClipboardDocumentListIcon },
  {
    name: "Billing",
    icon: CreditCardIcon,
    children: [
      { name: "Invoices", href: "/account/billing/invoices" },
      { name: "Payment Methods", href: "/account/billing/payments" },
    ],
  },
  {
    name: "Subscriptions",
    icon: ServerIcon,
    children: [{ name: "All Subscriptions", href: "/account/subscriptions" }],
  },
  { name: "Services", href: "/account/services", icon: Squares2X2Icon },
  {
    name: "Support",
    icon: ChatBubbleLeftRightIcon,
    children: [
      { name: "Cases", href: "/account/support" },
      { name: "New Case", href: "/account/support/new" },
    ],
  },
  {
    name: "Settings",
    href: "/account/settings",
    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");
  const currentItem = nav[subIdx];
  if (subIdx >= 0 && currentItem) {
    const dynamicChildren = (activeSubscriptions || []).map(sub => ({
      name: truncate(sub.productName || `Subscription ${sub.id}`, 28),
      href: `/account/subscriptions/${sub.id}`,
      tooltip: sub.productName || `Subscription ${sub.id}`,
    }));

    nav[subIdx] = {
      name: currentItem.name,
      icon: currentItem.icon,
      href: currentItem.href,
      isLogout: currentItem.isLogout,
      children: [{ name: "All Subscriptions", href: "/account/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)) + "…";
}
