import { useId, useState } from "react";
import "./tabs.css";

export type TabsVariant = "underline" | "segment" | "rounded";
export type TabsSize = "md" | "sm" | "xs";

export type TabsProps = {
  activeIndex?: number;
  ariaLabel?: string;
  className?: string;
  defaultActiveIndex?: number;
  dir?: "ltr" | "rtl";
  fullWidth?: boolean;
  items?: string[];
  onActiveIndexChange?: (index: number) => void;
  size?: TabsSize;
  variant?: TabsVariant;
};

export function Tabs({
  activeIndex,
  ariaLabel,
  className = "",
  defaultActiveIndex = 0,
  dir = "ltr",
  fullWidth = false,
  items = [],
  onActiveIndexChange,
  size = "md",
  variant = "underline",
}: TabsProps) {
  const rtl = dir === "rtl";
  const generatedId = useId();
  const [uncontrolledActiveIndex, setUncontrolledActiveIndex] = useState(defaultActiveIndex);
  const selectedIndex = activeIndex ?? uncontrolledActiveIndex;

  function selectTab(index: number) {
    if (activeIndex === undefined) {
      setUncontrolledActiveIndex(index);
    }

    onActiveIndexChange?.(index);
  }

  return (
    <div
      aria-label={ariaLabel}
      className={[
        "ds-tabs",
        `ds-tabs--${variant}`,
        `ds-tabs--${size}`,
        fullWidth ? "ds-tabs--full" : "ds-tabs--hug",
        rtl ? "ds-tabs--rtl" : "ds-tabs--ltr",
        className,
      ]
        .filter(Boolean)
        .join(" ")}
      dir={dir}
      role="tablist"
    >
      {items.map((item, index) => {
        const selected = selectedIndex === index;
        const tabId = `${generatedId}-tab-${index}`;
        const panelId = `${generatedId}-panel-${index}`;

        return (
          <button
            aria-controls={panelId}
            aria-selected={selected}
            className="ds-tabs__tab"
            id={tabId}
            key={`${item}-${index}`}
            onClick={() => selectTab(index)}
            role="tab"
            tabIndex={selected ? 0 : -1}
            type="button"
          >
            <span className="ds-tabs__content">
              <span className="ds-tabs__label">{item}</span>
            </span>
          </button>
        );
      })}
    </div>
  );
}
