import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useTabsContext } from "./tabs-context";

/** Props for Tabs.List. */
export interface TabsListProps extends JSX.HTMLAttributes<HTMLDivElement> {
  children?: JSX.Element;
}

/** Container for Tab elements. Handles arrow key navigation. */
export function TabsList(props: TabsListProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onKeyDown"]);
  const ctx = useTabsContext();

  const handleKeyDown: JSX.EventHandler<HTMLDivElement, KeyboardEvent> = (e) => {
    if (typeof local.onKeyDown === "function") local.onKeyDown(e);
    const isHorizontal = ctx.orientation() === "horizontal";
    const nextKey = isHorizontal ? "ArrowRight" : "ArrowDown";
    const prevKey = isHorizontal ? "ArrowLeft" : "ArrowUp";

    const tabs = Array.from(
      (e.currentTarget as HTMLDivElement).querySelectorAll<HTMLButtonElement>(
        "[role='tab']:not([disabled])",
      ),
    );
    const focused = document.activeElement as HTMLButtonElement;
    const index = tabs.indexOf(focused);
    if (index === -1) return;

    let next: HTMLButtonElement | undefined;
    if (e.key === nextKey) {
      e.preventDefault();
      next = tabs[(index + 1) % tabs.length];
    } else if (e.key === prevKey) {
      e.preventDefault();
      next = tabs[(index - 1 + tabs.length) % tabs.length];
    } else if (e.key === "Home") {
      e.preventDefault();
      next = tabs[0];
    } else if (e.key === "End") {
      e.preventDefault();
      next = tabs[tabs.length - 1];
    }

    if (next) {
      next.focus();
      if (ctx.activationMode() === "automatic") {
        const value = next.getAttribute("data-value");
        if (value) ctx.setActiveTab(value);
      }
    }
  };

  return (
    <div role="tablist" aria-orientation={ctx.orientation()} onKeyDown={handleKeyDown} {...rest}>
      {local.children}
    </div>
  );
}
