"use client";

import { Home } from "lucide-react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import React, { useMemo } from "react";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { humanizeSegment } from "@/lib/breadcrumb-utils";
import { getTenantWorkspaceBase, tenantHref } from "@/lib/tenant-routing";

export default function Topbar() {
  const pathname = usePathname();
  const params = useParams();
  const app = typeof params?.app === "string" ? params.app : undefined;

  const crumbs = useMemo(() => {
    const parts = (pathname || "").split("/").filter(Boolean);
    if (parts.length === 0) return [];

    const base = getTenantWorkspaceBase(pathname, app);
    const skip = base ? 1 : 0;
    const rest = parts.slice(skip);

    const items: { href: string; label: string; isLast: boolean }[] = [];

    items.push({
      href: tenantHref(pathname, "/dashboard", app),
      label: "Home",
      isLast: rest.length === 0 || (rest.length === 1 && rest[0] === "dashboard"),
    });

    rest.forEach((seg, idx) => {
      if (seg === "dashboard" && idx === 0) return;
      const hrefPath = `/${rest.slice(0, idx + 1).join("/")}`;
      const isLast = idx === rest.length - 1;
      items.push({
        href: tenantHref(pathname, hrefPath, app),
        label: humanizeSegment(seg),
        isLast,
      });
    });

    return items;
  }, [pathname, app]);

  if (crumbs.length === 0) {
    return (
      <div className="flex w-full items-center gap-2 px-3 py-1 text-sm shadow">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbPage className="text-muted-foreground">Dashboard</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>
      </div>
    );
  }

  return (
    <div className="flex w-full items-center gap-2 overflow-x-auto px-3 py-1 text-sm shadow">
      <Breadcrumb>
        <BreadcrumbList>
          {crumbs.map((c, i) => (
            <React.Fragment key={`${c.href}-${i}`}>
              {i > 0 ? <BreadcrumbSeparator /> : null}
              <BreadcrumbItem>
                {c.isLast ? (
                  <BreadcrumbPage>
                    {c.label === "Home" ? <Home className="size-4" /> : c.label}
                  </BreadcrumbPage>
                ) : (
                  <BreadcrumbLink asChild>
                    <Link href={c.href} className="inline-flex items-center gap-1">
                      {c.label === "Home" ? <Home className="size-4" /> : c.label}
                    </Link>
                  </BreadcrumbLink>
                )}
              </BreadcrumbItem>
            </React.Fragment>
          ))}
        </BreadcrumbList>
      </Breadcrumb>
    </div>
  );
}
