"use client";

import { useMemo, useState } from "react";

import { usePathname } from "next/navigation";

import Link from "next/link";

import { OxyfinzLogo } from "@/components/brand/oxyfinz-logo";
import {
  Sidebar,
  SidebarContent,
  SidebarHeader,
} from "@/components/ui/sidebar";
import {
  buildCustomerSidebarPanelsFromNavigation,
  getPanelIdForNavigationPath,
  type CustomerNavigationPayload,
} from "@/navigation/sidebar/dynamic-sidebar";
import {
  sidebarPanels,
  type SidebarPanelId,
} from "@/navigation/sidebar/frontend-items";
import { applyMacroLayoutToPanels } from "@/navigation/sidebar/macro-sidebar";
import { resolveMenuLayout, type InitialMenuLayout } from "@/app/customer/_lib/initial-menu-layout";
import { useDefaultLayout } from "@/app/customer/_lib/use-default-layout";
import { useAssetClassFilterCatalog } from "@/app/customer/[tenant]/reports/_shared/lib/use-asset-class-filter-catalog";
import { customerUrl, extractCustomerTenantFromPath } from "@/lib/tenant";

import { NavMain } from "./nav-main";
import { SidebarPanelRail } from "@/components/sidebar/sidebar-panel-rail";
import { SidebarShell } from "@/components/sidebar/sidebar-shell";

type AppSidebarProps = React.ComponentProps<typeof Sidebar> & {
  navigation?: CustomerNavigationPayload;
  allowedRoutes?: readonly string[];
  /** Real tenant slug from layout (required in host mode where path has no tenant segment). */
  customerTenant?: string | null;
  /** Server-resolved layout: paints the right menu before the browser has loaded it. */
  initialMenuLayout?: InitialMenuLayout | null;
};

export function AppSidebar({
  navigation,
  allowedRoutes,
  customerTenant: customerTenantProp = null,
  initialMenuLayout = null,
  ...props
}: AppSidebarProps) {
  const pathname = usePathname();
  const [selectedPanel, setSelectedPanel] = useState<{
    pathname: string;
    panel: SidebarPanelId;
  } | null>(null);

  const customerTenant = customerTenantProp || extractCustomerTenantFromPath(pathname);
  const live = useDefaultLayout(customerTenant ?? "");
  const { catalog: liveMacroCatalog } = useAssetClassFilterCatalog("macro", [], {
    enabled: Boolean(customerTenant) && (live.layout === "macro" || initialMenuLayout?.layout === "macro"),
  });
  const { layout, macroCatalog } = resolveMenuLayout({ initial: initialMenuLayout, live, liveMacroCatalog });
  const panels = useMemo(() => {
    if (!customerTenant) return sidebarPanels;
    const base = buildCustomerSidebarPanelsFromNavigation(customerTenant, navigation, allowedRoutes);
    return layout === "macro" ? applyMacroLayoutToPanels(base, macroCatalog) : base;
  }, [customerTenant, navigation, allowedRoutes, layout, macroCatalog]);
  const activePanel =
    selectedPanel?.pathname === pathname
      ? selectedPanel.panel
      : customerTenant
        ? getPanelIdForNavigationPath(pathname, panels)
        : "transactions";
  // Prefer tenant-scoped panels only — never fall back to unprefixed static URLs when tenant is known.
  const currentPanel =
    panels.find((panel) => panel.id === activePanel) ??
    panels[0] ??
    (!customerTenant ? sidebarPanels[0] : undefined);

  const handlePanelChange = (panel: SidebarPanelId) => {
    setSelectedPanel({ pathname, panel });
  };

  const homeHref = customerTenant ? customerUrl(customerTenant, "/dashboard") : "/dashboard";

  return (
    <SidebarShell homeHref={homeHref} header={null} {...props}>
      <div className="flex h-full min-h-0 w-full">
        <SidebarPanelRail panels={panels} activePanel={activePanel} onPanelChange={handlePanelChange} />

        <div className="flex min-w-0 flex-1 flex-col group-data-[collapsible=icon]:hidden">
          <SidebarHeader className="px-3 py-3">
            <Link
              prefetch={false}
              href={homeHref}
              className="inline-flex items-center"
              data-tutorial="home-link"
            >
              <OxyfinzLogo />
            </Link>
          </SidebarHeader>

          <SidebarContent>
            <div className="px-3 pb-1">
              <p className="text-[11px] font-medium tracking-wider text-sidebar-foreground/50 uppercase">
                {currentPanel?.label}
              </p>
            </div>
            <NavMain items={currentPanel?.groups ?? []} />
          </SidebarContent>
        </div>
      </div>
    </SidebarShell>
  );
}
