import type { ElementType, FC, HTMLAttributes } from 'react';
import classnames from 'classnames';
import React, { useContext } from 'react';
import { DropdownContext } from '../Dropdown/DropdownContext';

export interface DropdownToggleProps extends HTMLAttributes<HTMLElement> {
  tag?: ElementType;
}

const DropdownToggle: FC<DropdownToggleProps> = ({ children, className, tag: Tag = 'div', ...props }) => {
  const value = useContext(DropdownContext);

  return (
    <Tag
      className={classnames({ active: value.isOpen }, className)}
      data-testid="DropdownToggle"
      onClick={value.toggle}
      {...props}
    >
      {/* @ts-ignore todo: do we still need this function check? */}
      {typeof children === 'function' ? children(value) : children}
    </Tag>
  );
};

export default DropdownToggle;
