import React from 'react';
import PropTypes from 'prop-types';
import cx from "classnames"
import library from './assets/icon-map';
import SocialIcon, { lookupSocialIcon } from '../social-icon'
import Tooltip from '../tooltip'
import { IconButton } from '../button';

const SIZES = {
  sm: "w-4 h-4",
  md: "w-6 h-6",
  lg: "w-8 h-8"
}

const lookupIcon = iconName => library.find(i => i.name === iconName)

const FallbackIcon = ({ icon, ...props }) => {
  const iconName = icon.iconName ?? "FontAwesome"
  console.warn(`Use of ${iconName} icon is deprecated unless for social. Use social icons directly from SocialIcon component instead, or use the correct icon name from the component library's icon tokens`)
  return <SocialIcon icon={icon} {...props} />
}

const Icon = ({ name, className, size = "md", ...props }) => {
  className = cx(
    "fill-current inline-block overflow-visible",
    SIZES[size],
    className,
  )

  if (name && typeof name == 'string') {
    const icon = lookupIcon(name)
    if (!icon) {
      const socialIcon = lookupSocialIcon(name)
      if(!socialIcon) {
        const message = `The icon "${name}" you're trying to use doesn't exist. See available icons in the component library's icon tokens`
        console.warn(message)
        return (
          <Tooltip label={message}>
            <IconButton icon="question-circle" label={message} className="text-red-600 animate-bounce" />
          </Tooltip>
        )
      }
      return <FallbackIcon icon={socialIcon} className={className} {...props} />
    }

    const IconComponent = icon.component

    return <IconComponent className={className} name={name} style={{ fontSize: 'inherit' }} {...props} />
  }

  return <FallbackIcon icon={name} className={className} {...props} />
};

Icon.propTypes = {
  /** Matches name in Figma, using lowercase and hyphens instead of spaces. */
  name: PropTypes.string.isRequired,
  size: PropTypes.oneOf(["sm", "md", "lg"]),
  /** Customize the icon. E.g. text-gray-700 */
  className: PropTypes.string,
}

export default Icon;
