"use client";

import { Suspense } from "react";
import { useSelectedLayoutSegment } from "next/navigation";
import Link, { useLinkStatus } from "next/link";
import "./SegmentTabs.css";

interface SegmentTabsProps {
  segments: Array<{
    segment: string | null;
    title: string;
    children?: React.ReactNode;
    href?: string;
  }>;
  basePath?: string;
}

function TabContent({
  title,
  children,
  isActive,
}: {
  title: string;
  children?: React.ReactNode;
  isActive: boolean;
}) {
  const { pending } = useLinkStatus();
  const className = pending
    ? "SegmentTabs-tabText--pending"
    : isActive
      ? "SegmentTabs-tabText--active"
      : undefined;
  return (
    <span className={className}>
      {title}
      {children}
    </span>
  );
}

export function SegmentTabs({ segments, basePath = "/" }: SegmentTabsProps) {
  return (
    <Suspense fallback={<SegmentTabsShim segments={segments} basePath={basePath} />}>
      <SegmentTabsLoaded segments={segments} basePath={basePath} />
    </Suspense>
  );
}

export function SegmentTabsShim({ segments, basePath }: SegmentTabsProps) {
  return <SegmentTabsBase selected={null} segments={segments} basePath={basePath} />;
}

export function SegmentTabsLoaded({ segments, basePath }: SegmentTabsProps) {
  const selected = useSelectedLayoutSegment();
  return <SegmentTabsBase selected={selected} segments={segments} basePath={basePath} />;
}

export function SegmentTabsBase({
  segments,
  basePath,
  selected,
}: SegmentTabsProps & { selected: string | null }) {
  return (
    <nav className="SegmentTabs">
      {segments.map((segment) => {
        const isActive = selected === segment.segment;
        return (
          <Link
            key={segment.segment}
            href={segment.href ?? basePath + (segment.segment ?? "")}
            className={`SegmentTabs-tab ${isActive ? "SegmentTabs-tab--active" : ""}`}
          >
            <TabContent title={segment.title} isActive={isActive}>
              {segment.children}
            </TabContent>
          </Link>
        );
      })}
    </nav>
  );
}
