import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { useTabContext } from './TabsProvider';

const propTypes = {
  /**
   * Children to set inside the Tabs.
   */
  children: PropTypes.node,
  /**
   * The default class for the Tab.
   */
  defaultClassname: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  /**
   * The name of the tab.
   */
  name: PropTypes.string.isRequired,
  /**
   * Property to disable the tab. The tab won't be clickable and focusable with
   * keyboard events.
   */
  isDisabled: PropTypes.bool,
  /**
   * Property to select the tab. You may not need this prop as it is mainly used
   * internally.
   */
  isSelected: PropTypes.bool,
  /**
   * The custom tag for the root of the Tab
   */
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
};

const defaultProps = {
  children: '',
  defaultClassname: 'sui-m-tabs__item',
  isDisabled: false,
  isSelected: false,
  tag: 'button',
};

export const Tab = forwardRef(({
  defaultClassname,
  name,
  isDisabled,
  isSelected,
  tag: Tag,
  ...attributes
}, ref) => {
  const { id } = useTabContext();

  const classes = classnames(
    defaultClassname,
    {
      'as--active': isSelected,
      'as--disabled': isDisabled,
    },
  );

  return (
    <Tag
      aria-controls={`panel:${id}:${name}`}
      aria-selected={isSelected}
      className={classes}
      id={`tab:${id}:${name}`}
      ref={ref}
      role="tab"
      tabIndex={isSelected ? 0 : -1}
      type="button"
      {...attributes}
    />
  );
});

Tab.propTypes = propTypes;
Tab.defaultProps = defaultProps;
