import * as React from 'react';
import classNames from 'classnames';
import './index.less';
// import './style.less';
import { ConfigProvider } from 'antd';
import { ComponentType, CSSProperties } from 'react';
import AntIcon from '@ant-design/icons';
import { CustomIconComponentProps } from '@ant-design/icons/lib/components/Icon';
import {
  addCollection,
  Icon as Iconify,
  IconifyJSON,
} from '@iconify-icon/react';
import iconJson from './iconify.json';

interface IconProps {
  iconName?: string;
  style?: CSSProperties;
  spin?: boolean;
  className?: string;
  onClick?: React.MouseEventHandler<HTMLDivElement>;
  component?: ComponentType<CustomIconComponentProps>;
  rotate?: number;
  provider?: string;
}

const Icon = (props: IconProps) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = React.useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-icon');

  const {
    iconName,
    style = {},
    spin = false,
    onClick = () => {},
    rotate,
  } = props;
  React.useEffect(() => {
    addCollection(iconJson, 'mbt20240226');
  }, []);

  function toLine(name: string) {
    const nameArr = name.match(/([A-Z][a-z]*|\d+)/g);
    const resName = nameArr?.reduce((pre, cur, index) => {
      if (index === 0) {
        return cur.toLowerCase();
      }
      return pre + '-' + cur.toLowerCase();
    }, '');

    return resName;
  }

  return iconName ? (
    <div
      className={classNames(`${prefixCls}-box`, props.className)}
      style={{ transform: `rotate(${rotate}deg)`, ...style }}
      onClick={onClick}
    >
      <div
        className={classNames('i-icon', {
          animation: spin,
        })}
      >
        <Iconify
          icon={`@${props.provider || 'mbt20240226'}:ibuilding:${toLine(
            iconName,
          )}`}
        ></Iconify>
      </div>
    </div>
  ) : (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    <AntIcon {...(props as any)}></AntIcon>
  );
};

Icon.addCollection = (iconifyJson: IconifyJSON, provider: string) => {
  const res = addCollection(iconifyJson, provider);
  return res;
};

export { Icon };
