import { clsx } from 'clsx';
import { forwardRef, useEffect, useRef } from 'react';
import { useEffectEvent } from '../common/hooks/useEffectEvent';

export interface TabProps {
  children?: React.ReactNode;
  disabled?: boolean;
  selected?: boolean;
  id: string;
  panelId: string;
  style?: React.CSSProperties;
  focusTab?: () => void;
  onKeyDown: React.KeyboardEventHandler<HTMLLIElement>;
  onClick?: React.MouseEventHandler<HTMLLIElement>;
}

const noop = () => {};

const Tab = forwardRef(function Tab(
  {
    children,
    id,
    disabled,
    panelId,
    selected,
    onKeyDown,
    onClick,
    style,
    focusTab = noop,
  }: TabProps,
  reference: React.ForwardedRef<HTMLLIElement>,
) {
  const handleFocusTab = useEffectEvent(focusTab);
  const firstUpdate = useRef(true);
  useEffect(
    function checkFocus() {
      if (firstUpdate.current) {
        firstUpdate.current = false;
        return;
      }

      if (selected) {
        handleFocusTab();
      }
    },
    [handleFocusTab, selected],
  );

  return (
    <li
      ref={reference}
      className={clsx('tabs__tab', selected ? 'np-text-body-large-bold' : 'np-text-body-large', {
        'tabs__tab--selected': selected,
        clickable: !disabled,
        disabled,
      })}
      role="tab"
      id={id}
      aria-selected={selected ? 'true' : 'false'}
      aria-disabled={disabled ? 'true' : 'false'}
      aria-controls={disabled ? undefined : panelId}
      tabIndex={0}
      style={style}
      onKeyDown={disabled ? undefined : onKeyDown}
      onClick={onClick}
    >
      <span className="tabs__tab__content">{children}</span>
    </li>
  );
});

export default Tab;
