import React, {
  Children,
  ReactElement,
  cloneElement,
  useState,
  useEffect,
} from "react";
import classNames from "classnames";
import { bem } from "../../utilities/bem";
import { Box, BoxProps } from "../Box";
import { Icon, ICON_TYPE } from "../Icon";

const cn = "VendorLogo";

export type VendorLogoSize = 4 | 6 | 10 | 14 | 20 | 40;

interface VendorLogoBadgeProps extends BoxProps {
  icon: ICON_TYPE;
  size?: VendorLogoSize;
}

interface VendorLogoProps extends BoxProps {
  /**
   * Name of the vendor.  If a logo image src is not provided, a tile with the first letter of the `vendorName` will be shown instead
   */
  vendorName: string;
  /**
   * Specifies the path to the logo image
   */
  src?: string;
  /**
   * Specifies an alternate label for the image
   */
  alt?: string;
  /**
   * Sets the size of logo. Uses select tailwind height tokens.  Valid values are 4, 6, 10, 14, 20, 40.
   */
  size?: VendorLogoSize;
  /**
   * Optional `VendorLogo.Badge`
   */
  children?: ReactElement<VendorLogoBadgeProps>;
}

const VendorLogoBadge = ({
  icon,
  size = 10,
  className,
  ...rest
}: VendorLogoBadgeProps) => {
  return (
    <Box
      className={classNames(bem(cn, { e: "badge" }), className)}
      style={{
        fontSize: `${size}px`,
      }}
      {...rest}
    >
      <Icon className={bem(cn, { e: "icon" })} icon={icon} />
    </Box>
  );
};

export const VendorLogo = ({
  src,
  vendorName,
  alt,
  className,
  size = 10,
  children,
}: VendorLogoProps) => {
  const [loadSuccess, setLoadSuccess] = useState(!!src);
  const firstLetter = vendorName && vendorName.length > 0 ? vendorName[0] : "";

  useEffect(() => {
    setLoadSuccess(!!src);
  }, [src]);

  return (
    <Box className={classNames(`${bem(cn)} w-${size} h-${size}`, className)}>
      {loadSuccess ? (
        <img
          className={bem(cn, { e: "img" })}
          src={src}
          alt={alt || vendorName || ""}
          onError={() => {
            setLoadSuccess(false);
          }}
        />
      ) : (
        <Box
          className={bem(cn, { e: "placeholder" })}
          style={{
            fontSize: `${size * 1.6}px`,
          }}
        >
          {firstLetter.toUpperCase()}
        </Box>
      )}

      {Children.map(children, (child) => {
        return cloneElement(child as ReactElement, {
          size,
        });
      })}
    </Box>
  );
};

VendorLogo.Badge = VendorLogoBadge;
