"use client";

import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type ComponentType,
  type ReactNode,
  type Ref,
} from "react";

/** One tab of {@link UnderlineTabs}, with an already-translated label. */
export type UnderlineTab<Id extends string> = {
  id: Id;
  label: string;
};

/** A tab that is a link (route or query-parameter tabs). */
export type UnderlineLinkTab<Id extends string> = UnderlineTab<Id> & {
  href: string;
};

/**
 * The link element of link tabs, e.g. Next's `Link`. Gets `replace` and
 * `scroll={false}` when {@link UnderlineTabs} is given `replace`.
 */
export type UnderlineTabsLink = ComponentType<UnderlineTabsLinkProps>;

/** The props {@link UnderlineTabs} passes to its {@link UnderlineTabsLink}. */
export type UnderlineTabsLinkProps = {
  href: string;
  replace?: boolean;
  scroll?: boolean;
  className?: string;
  "aria-current"?: "page";
  ref?: Ref<HTMLAnchorElement>;
  children?: ReactNode;
};

type UnderlineTabsCommon<Id extends string> = {
  /** The tab that is underlined, or `null` for none. */
  activeId: Id | null;
  /** Accessible name of the tab row. */
  ariaLabel: string;
};

/** Props of {@link UnderlineTabs}: link tabs or in-memory tabs. */
export type UnderlineTabsProps<Id extends string> = UnderlineTabsCommon<Id> &
  (
    | {
        tabs: readonly UnderlineLinkTab<Id>[];
        /** Renders each tab; default a plain `<a>`. */
        linkComponent?: UnderlineTabsLink;
        /**
         * Swap the history entry instead of adding one (tabs that are query
         * parameters of one page); the page keeps its scroll position then.
         */
        replace?: boolean;
        onSelect?: never;
      }
    | {
        tabs: readonly UnderlineTab<Id>[];
        /** In-memory tabs: each tab is a button that calls this. */
        onSelect: (id: Id) => void;
        linkComponent?: never;
        replace?: never;
      }
  );

const TAB_CLASS =
  "-mb-px inline-flex min-h-11 shrink-0 items-center whitespace-nowrap border-b-2 body-normal transition-colors hover:text-foreground-default";
const ACTIVE_CLASS = "border-foreground-red-orange text-foreground-default";
const IDLE_CLASS = "border-transparent text-foreground-muted";

// The default link of link tabs (`replace` / `scroll` need a router link).
function PlainLink({
  ref,
  href,
  className,
  children,
  "aria-current": ariaCurrent,
}: UnderlineTabsLinkProps) {
  return (
    <a ref={ref} href={href} className={className} aria-current={ariaCurrent}>
      {children}
    </a>
  );
}

/**
 * The shared underline tab row (portal Account and Settings, the tracking
 * app's Settings): one tab per entry, the active one underlined in
 * red-orange. When the row is wider than its box it scrolls sideways, a fade
 * (with a › on the end side) marks the cut-off side, and the active tab is
 * scrolled into view.
 *
 * Router-agnostic: link tabs render through `linkComponent` (the portal passes
 * Next's `Link`); in-memory tabs (`onSelect`) render as buttons. Either way
 * the active tab carries `aria-current="page"`.
 */
export function UnderlineTabs<Id extends string>(props: UnderlineTabsProps<Id>) {
  const { tabs, activeId, ariaLabel } = props;
  const activeRef = useRef<HTMLElement>(null);
  const { navRef, edges, updateEdges } = useScrollEdges();
  useEffect(() => {
    const el = activeRef.current;
    if (el && typeof el.scrollIntoView === "function") {
      el.scrollIntoView({ inline: "center", block: "nearest" });
    }
    updateEdges();
    // The tab count can change once data loads, which shifts the row.
  }, [activeId, tabs.length, updateEdges]);

  return (
    <div className="relative -mb-1 border-b border-surface-stroke">
      <nav
        ref={navRef}
        onScroll={updateEdges}
        aria-label={ariaLabel}
        // Sideways only: `overflow-x-auto` alone makes the y axis scrollable
        // too (CSS computes it to auto), and the tabs' `-mb-px` overhang gave it
        // a pixel to scroll — the row wobbled up and down under a finger.
        // `touch-pan-x` hands vertical drags to the page.
        className="scrollbar-none flex touch-pan-x items-stretch gap-4 overflow-x-auto overflow-y-hidden sm:gap-6"
      >
        {tabs.map((tab) => {
          const isActive = tab.id === activeId;
          const className = `${TAB_CLASS} ${isActive ? ACTIVE_CLASS : IDLE_CLASS}`;
          const current = isActive ? ("page" as const) : undefined;
          if (props.onSelect) {
            const onSelect = props.onSelect;
            return (
              <button
                key={tab.id}
                type="button"
                ref={isActive ? (activeRef as Ref<HTMLButtonElement>) : undefined}
                aria-current={current}
                onClick={() => onSelect(tab.id)}
                className={className}
              >
                {tab.label}
              </button>
            );
          }
          const Link = props.linkComponent ?? PlainLink;
          const replace = props.replace ?? false;
          return (
            <Link
              key={tab.id}
              ref={isActive ? (activeRef as Ref<HTMLAnchorElement>) : undefined}
              href={(tab as UnderlineLinkTab<Id>).href}
              replace={replace}
              scroll={replace ? false : undefined}
              aria-current={current}
              className={className}
            >
              {tab.label}
            </Link>
          );
        })}
      </nav>
      {edges.start && (
        <span
          aria-hidden="true"
          className="pointer-events-none absolute inset-y-0 left-0 w-8 bg-gradient-to-r from-background to-transparent"
        />
      )}
      {edges.end && (
        <span
          aria-hidden="true"
          className="pointer-events-none absolute inset-y-0 right-0 flex w-10 items-center justify-end bg-gradient-to-l from-background to-transparent text-foreground-muted"
        >
          ›
        </span>
      )}
    </div>
  );
}

/**
 * Whether a sideways-scrolling row has more content cut off at its start or
 * end; re-measured on scroll, on resize and when `updateEdges` is called.
 */
function useScrollEdges() {
  const navRef = useRef<HTMLElement>(null);
  const [edges, setEdges] = useState({ start: false, end: false });
  const updateEdges = useCallback(() => {
    const el = navRef.current;
    if (!el) return;
    const start = el.scrollLeft > 1;
    const end = el.scrollLeft + el.clientWidth < el.scrollWidth - 1;
    setEdges((prev) =>
      prev.start === start && prev.end === end ? prev : { start, end },
    );
  }, []);
  useEffect(() => {
    const el = navRef.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(updateEdges);
    observer.observe(el);
    return () => observer.disconnect();
  }, [updateEdges]);
  return { navRef, edges, updateEdges };
}
