import cx from "classnames";

interface TabProps
  extends React.HTMLAttributes<HTMLButtonElement | HTMLAnchorElement> {
  /** Id of the tabpanel this tab controls. */
  controls?: string;
  href?: string;
  /** Active state */
  isActive?: boolean;
  /** Disabled state. */
  isDisabled?: boolean;
  className?: string;
  children?: React.ReactNode;
}

const CLASS_TABLIST_ITEM = "tab-list__item";
const CLASS_TABLIST_TAB = "tab-list__tab";

const Tab: React.FC<TabProps> = ({
  href,
  children,
  className,
  controls,
  isDisabled,
  isActive,
  ...other
}) => {
  const tabClasses = cx(CLASS_TABLIST_TAB, className);

  const tabindex = isActive ? 0 : -1;

  const Tag = href ? "a" : "button";

  return (
    <li className={CLASS_TABLIST_ITEM} role="presentation">
      <Tag
        type={href ? undefined : "button"}
        role={href ? undefined : "tab"}
        href={href}
        className={tabClasses}
        aria-selected={isActive}
        aria-controls={controls || undefined}
        tabIndex={tabindex}
        aria-disabled={isDisabled}
        {...other}
      >
        {children}
      </Tag>
    </li>
  );
};

Tab.displayName = "Tab";

export { Tab };
