"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { ADMIN_BASE } from "@/modules/_config/admin-nav";
import { useAdminProfile } from "@/stores/admin-session";
import React from "react";

const DRAW_ROUTE_LABELS: Record<string, string> = {
  finance: "Draw Finance",
  review: "Review",
  results: "Results",
};

const NAV_TRANSLATION_KEYS: Record<string, string> = {
  dashboard: "dashboard",
  admin_users: "admin_users",
  admin_roles: "admin_roles",
  players: "players",
  currencies: "currencies",
  wallet: "wallet",
  draws: "draws",
  config: "config",
  risk: "risk",
  settlement: "settlement",
  reconcile: "reconcile",
  tickets: "tickets",
  audit: "audit",
  settings: "settings",
};

const SETTINGS_ROUTE_LABELS: Record<string, string> = {
  currencies: "currencies.title",
};

function titleCase(value: string): string {
  return value
    .split("-")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}

type BreadcrumbCrumb = {
  label: string;
  href: string;
  isCurrent: boolean;
};

export function AdminBreadcrumb() {
  const { t } = useTranslation(["common", "dashboard", "audit", "config", "draws"]);
  const pathname = usePathname();
  const profile = useAdminProfile();
  const navItems = profile?.navigation ?? [];

  // Split the current path into segments.
  const segments = pathname.split("/").filter(Boolean);

  // Base breadcrumb: home / dashboard.
  const breadcrumbs: BreadcrumbCrumb[] = [
    {
      label: t("nav.home", { ns: "common" }),
      href: ADMIN_BASE,
      isCurrent: pathname === ADMIN_BASE,
    },
  ];

  if (pathname !== ADMIN_BASE) {
    const businessSegment = segments[1];
    if (businessSegment) {
      const navItem = navItems.find((item) => {
        return item.segment === businessSegment || item.href.includes(businessSegment);
      });

      if (navItem && navItem.href !== ADMIN_BASE) {
        const translatedNavLabel =
          NAV_TRANSLATION_KEYS[navItem.segment] != null
            ? t(`nav.${NAV_TRANSLATION_KEYS[navItem.segment]}`, {
                ns: "common",
                defaultValue: navItem.label,
              })
            : navItem.label;
        breadcrumbs.push({
          label: translatedNavLabel,
          href: navItem.href,
          isCurrent: pathname === navItem.href || segments.length === 2,
        });
      } else {
        breadcrumbs.push({
          label: t(`nav.${businessSegment}`, {
            ns: "common",
            defaultValue: titleCase(businessSegment),
          }),
          href: `${ADMIN_BASE}/${businessSegment}`,
          isCurrent: segments.length === 2,
        });
      }

      if (segments.length > 2) {
        const subSegment = segments[2];
        let subLabel = "";
        if (businessSegment === "config" && subSegment) {
          subLabel = t(`nav.items.${subSegment}`, { ns: "config", defaultValue: titleCase(subSegment) });
        } else if (businessSegment === "settings" && subSegment) {
          subLabel = t(SETTINGS_ROUTE_LABELS[subSegment] ?? `settings.${subSegment}`, {
            ns: "config",
            defaultValue: titleCase(subSegment),
          });
        } else {
          subLabel = subSegment
            ? t(`subnav.${subSegment}`, {
                ns: "draws",
                defaultValue: DRAW_ROUTE_LABELS[subSegment] ?? titleCase(subSegment),
              })
            : "";
        }
        if (subLabel) {
          breadcrumbs.push({
            label: subLabel,
            href: pathname,
            isCurrent: true,
          });
        }
      }
    }
  }

  return (
    <Breadcrumb>
      <BreadcrumbList className="gap-1">
        {breadcrumbs.map((crumb, index) => {
          const isLast = index === breadcrumbs.length - 1;
          const itemKey = `${crumb.href}-${index}`;

          return (
            <React.Fragment key={itemKey}>
              <BreadcrumbItem>
                {crumb.isCurrent ? (
                  <BreadcrumbPage>{crumb.label}</BreadcrumbPage>
                ) : (
                  <BreadcrumbLink render={<Link href={crumb.href} />}>{crumb.label}</BreadcrumbLink>
                )}
              </BreadcrumbItem>
              {!isLast && <BreadcrumbSeparator />}
            </React.Fragment>
          );
        })}
      </BreadcrumbList>
    </Breadcrumb>
  );
}
