import {
  MenuProps,
  Menu,
  ConfigProvider,
  Dropdown as OldDropdown,
  DropdownProps,
} from 'antd';
import React, { useContext, useState } from 'react';
import { Button } from '../Button';
import { Icon } from '../Icon';
import './index.less';
import { AOP } from '../utils/AOP';
import classNames from 'classnames';

interface DropdownExtraProps {
  menuItems?: MenuProps['items'];
  menuClick?: (e: any) => void;
  type?: 'text' | 'button';
  text?: string;
  showArrow?: boolean;
}

const Dropdown: any = ({
  menuItems = [],
  overlay,
  menuClick,
  onVisibleChange,
  className,
  type,
  text,
  children,
  showArrow = true,
  ...props
}: DropdownProps & DropdownExtraProps) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-dropdown');

  const [iconName, setIconName] = useState('DownSmall');

  const newMenuClick = new AOP(menuClick)
    .before(() => {
      setIconName('DownSmall');
    })
    .getFunction();

  const getMenu = () => {
    if (menuItems.length) {
      return (
        <Menu
          className={`${prefixCls}-menu`}
          selectable
          items={menuItems}
          onClick={newMenuClick}
        />
      );
    } else {
      return overlay;
    }
  };

  const newVisibleChange = new AOP(onVisibleChange)
    .before((e: any) => {
      setIconName(e ? 'UpSmall' : 'DownSmall');
    })
    .getFunction();

  const getChildren = () => {
    if (type) {
      const hastriggerClick =
        props.trigger && props.trigger.indexOf('click') > -1;
      const p: any = {
        className: `${prefixCls}-btn--${type}`,
      };
      if (showArrow) p.afterIcon = <Icon iconName={iconName} />;
      if (type === 'text') p.type = 'text';
      if (hastriggerClick && iconName === 'UpSmall')
        p.className += ` ${prefixCls}-btn--active`;
      return <Button {...p}>{text}</Button>;
    } else {
      return children;
    }
  };

  return (
    <OldDropdown
      {...props}
      overlay={getMenu()}
      onVisibleChange={newVisibleChange}
      className={classNames(`${prefixCls}-box`, className)}
    >
      {getChildren()}
    </OldDropdown>
  );
};

Dropdown.Button = OldDropdown.Button;

export { Dropdown };
