import React, { forwardRef } from "react";
import classNames from "classnames";
import { Icon } from "../icon";
import { useConfig } from "../_util/config-context";
import { callBoth } from "../_util/call-both";
import { StyledProps } from "../_type";

export interface TabItemProps extends StyledProps {
  label: React.ReactNode;
  actived: boolean;
  disabled: boolean;
  onClose: (evt: React.MouseEvent) => void;
  onClick: (evt: React.MouseEvent) => void;
  render: (children: JSX.Element) => JSX.Element;
}

export const TabItem = forwardRef(
  (
    {
      label,
      onClick,
      actived,
      disabled,
      onClose,
      render,
      className,
      style,
    }: TabItemProps,
    ref: React.Ref<HTMLLIElement>
  ) => {
    const { classPrefix } = useConfig();
    const children = render(<>{label}</>);
    const handleClick = disabled ? null : onClick;
    return (
      <li
        className={classNames(`${classPrefix}-tabs__tabitem`, className)}
        style={style}
        ref={ref}
      >
        {React.cloneElement(children, {
          className: classNames(
            `${classPrefix}-tabs__tab`,
            children.props.className,
            {
              "is-active": actived,
              "is-disabled": disabled,
            }
          ),
          onClick: callBoth(handleClick, children.props.onClick),
        })}
        {onClose && (
          <a className={`${classPrefix}-tabs__remove`} onClick={onClose}>
            <Icon type="dismiss" />
          </a>
        )}
      </li>
    );
  }
);
TabItem.displayName = "TabItem";
