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

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

const lookupIcon = iconName => library.find(i => {
  if (i.name === iconName) {
    return i.component
  }
})

const FallbackIcon = ({ icon, ...props }) => {
  const iconName = icon.iconName ?? "FontAwesome"
  console.warn(`Use of ${iconName} icon is deprecated unless for social. Please use one of the icons from the CKIcon library.`)
  return <SocialIcon icon={icon} {...props} />
}

const CKIcon = ({ 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) {
        return (
          <div>
            Sorry looks like the icon you are looking for does not exist.
          </div>
        )
      }
      return <FallbackIcon icon={socialIcon} className={className} {...props} />
    }

    const Icon = icon.component

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

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

CKIcon.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 CKIcon;
