"use client";

import { useState } from "react";

import { usePathname } from "next/navigation";

import Link from "next/link";

import { OxyfinzLogo } from "@/components/brand/oxyfinz-logo";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  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 { customerUrl, extractCustomerTenantFromPath } from "@/lib/tenant";

import { NavMain } from "./nav-main";
import { NavUser } from "./nav-user";
import { NavUserSkeleton } from "@/components/sidebar/nav-user-skeleton";
import { SidebarPanelRail } from "@/components/sidebar/sidebar-panel-rail";
import { SidebarShell } from "@/components/sidebar/sidebar-shell";
import type { HeaderUser } from "./account-switcher";

type AppSidebarProps = React.ComponentProps<typeof Sidebar> & {
  sessionUser?: HeaderUser | null;
  impersonated?: boolean;
  impersonationType?: "admin" | "corporate" | null;
  navigation?: CustomerNavigationPayload;
  allowedRoutes?: readonly string[];
  /** Real tenant slug from layout (required in host mode where path has no tenant segment). */
  customerTenant?: string | null;
};

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

  const customerTenant = customerTenantProp || extractCustomerTenantFromPath(pathname);
  const panels = customerTenant
    ? buildCustomerSidebarPanelsFromNavigation(customerTenant, navigation, allowedRoutes)
    : sidebarPanels;
  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 navUser = sessionUser;

  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">
              <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>

          <SidebarFooter>
            {navUser ? (
              <NavUser
                user={navUser}
                impersonated={impersonated}
                impersonationType={impersonationType}
                customerTenant={customerTenant}
              />
            ) : (
              <NavUserSkeleton />
            )}
          </SidebarFooter>
        </div>
      </div>
    </SidebarShell>
  );
}
