"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  HomeIcon,
  SearchIcon,
  ProductIcon,
  TrendIcon,
  CreatorsIcon,
  StoreIcon,
  TikTokAccountIcon,
  VideoIcon,
  StarIcon,
  ReportIcon,
  AiIcon,
  BillingIcon,
  IntegrationIcon,
  SettingsIcon,
} from "@/components/dashboard/reference-icons";
import { useLanguage } from "@/lib/i18n/context";
import {
  dashboardRoutesForGroup,
  isDashboardNavRouteActive,
  type DashboardNavItemKey,
  type DashboardNavGroupKey,
} from "@/components/dashboard/dashboard-nav-config";

interface NavItem {
  tone: "cyan" | "blue" | "purple" | "pink" | "green";
  href: string;
  icon: (props: { className?: string }) => React.ReactElement;
  label: string;
  isActive?: (pathname: string) => boolean;
}

interface NavGroup {
  label: string | null;
  items: NavItem[];
}

/** Sidebar order mirrors the expected customer product surface. The route
 * list itself lives in dashboard-nav-config.ts so active-state and link
 * coverage are deterministic and unit-testable outside React. */
export function useDashboardNavGroups(): NavGroup[] {
  const { t } = useLanguage();
  const n = t.dashboard.nav;
  const labels: Record<DashboardNavItemKey, string> = {
    overview: n.overview,
    marketExplorer: n.products,
    products: n.productsCatalog,
    trends: n.trends,
    creators: n.creators,
    stores: n.stores,
    videos: n.videos,
    saved: n.saved,
    tiktokAccount: n.tiktokAccount,
    reports: n.reports,
    assistant: n.ai,
    billing: n.billing,
    integrations: n.integrations,
    settings: n.settings,
  };
  const icons: Record<DashboardNavItemKey, NavItem["icon"]> = {
    overview: HomeIcon,
    marketExplorer: SearchIcon,
    products: ProductIcon,
    trends: TrendIcon,
    creators: CreatorsIcon,
    stores: StoreIcon,
    videos: VideoIcon,
    saved: StarIcon,
    tiktokAccount: TikTokAccountIcon,
    reports: ReportIcon,
    assistant: AiIcon,
    billing: BillingIcon,
    integrations: IntegrationIcon,
    settings: SettingsIcon,
  };
  const tones: Record<DashboardNavItemKey, NavItem["tone"]> = {
    overview: "cyan",
    marketExplorer: "cyan",
    products: "cyan",
    trends: "blue",
    creators: "purple",
    stores: "blue",
    videos: "pink",
    saved: "cyan",
    tiktokAccount: "purple",
    reports: "blue",
    assistant: "purple",
    billing: "green",
    integrations: "purple",
    settings: "blue",
  };
  const toItems = (group: DashboardNavGroupKey): NavItem[] =>
    dashboardRoutesForGroup(group).map((route) => ({
      tone: tones[route.key],
      href: route.href,
      icon: icons[route.key],
      label: labels[route.key],
      isActive: (pathname) => isDashboardNavRouteActive(pathname, route),
    }));

  return [
    { label: null, items: toItems("root") },
    { label: n.groups.research, items: toItems("research") },
    { label: n.groups.workspace, items: toItems("workspace") },
    { label: n.groups.account, items: toItems("account") },
  ];
}

export function DashboardNav({
  onNavigate,
  showBillingWarning = false,
}: {
  onNavigate?: () => void;
  /** Shown as a dot on the Billing item when payment failed, action is
   * required, or a cancellation is scheduled — see getUserPlan(). */
  showBillingWarning?: boolean;
}) {
  const pathname = usePathname();
  const groups = useDashboardNavGroups();

  return (
    <>
      {groups.map((group) => {
        const isBare = group.label === null;
        const items = group.items.map((item) => {
          const active = item.isActive
            ? item.isActive(pathname)
            : item.href === "/dashboard"
              ? pathname === "/dashboard"
              : pathname.startsWith(item.href);
          const isBilling = item.href === "/dashboard/billing";
          return (
            <Link
              key={`${item.href}-${item.label}`}
              href={item.href}
              onClick={onNavigate}
              aria-current={active ? "page" : undefined}
              className={`nav-item nav-tone-${item.tone}${active ? " active" : ""}`}
              style={{ position: isBilling && showBillingWarning ? "relative" : undefined }}
            >
              <span className="nav-icon-shell"><item.icon /></span>
              {item.label}
              {isBilling && showBillingWarning && (
                <span
                  aria-hidden="true"
                  style={{
                    position: "absolute",
                    top: 8,
                    right: 10,
                    width: 6,
                    height: 6,
                    borderRadius: "50%",
                    background: "var(--accent-2)",
                  }}
                />
              )}
            </Link>
          );
        });
        return isBare ? (
          <span key="overview">{items}</span>
        ) : (
          <div className="nav-group" key={group.label}>
            <div className="nav-label">{group.label}</div>
            {items}
          </div>
        );
      })}
    </>
  );
}
