import * as React from 'react';
import styled from 'styled-components';

import { CDNIcon } from '@redocly/theme/icons/CDNIcon/CDNIcon';
import { resolveIcon } from '@redocly/theme/core/utils';
import { InlineSvg } from '@redocly/theme/markdoc/components/InlineSvg/InlineSvg';
import { Image } from '@redocly/theme/components/Image/Image';

export type GenericIconProps = {
  icon: string | React.ReactNode;
  srcSet?: string;
  rawContent?: string;
  size?: string;
  color?: string;
  alt?: string;
  className?: string;
};

const INVALID_ICON_NAME = 'image-slash';

export function GenericIcon({
  icon,
  srcSet,
  rawContent,
  size,
  color,
  alt,
  className,
}: GenericIconProps) {
  if (srcSet) {
    return <IconSrcSetImg srcSet={srcSet} alt={alt} className={className} />;
  }

  const resolvedIcon = icon && typeof icon === 'string' ? resolveIcon(icon) : null;
  const iconComponent = rawContent ? (
    <IconSvg fileRawContent={rawContent} className={className} />
  ) : resolvedIcon?.type === 'link' ? (
    <IconImg src={resolvedIcon.value} alt={alt} className={className} />
  ) : resolvedIcon?.type === 'font-awesome' ? (
    <CDNIcon
      name={resolvedIcon.name}
      type={resolvedIcon.style}
      size={size}
      color={color}
      className={className}
    />
  ) : resolvedIcon?.type === 'invalid' ? (
    <CDNIcon name={INVALID_ICON_NAME} size={size} color={color} className={className} />
  ) : (
    icon
  );

  return iconComponent;
}

const IconImg = styled.img`
  width: var(--icon-width, 16px);
  height: var(--icon-height, 16px);
  display: inline-block;
  vertical-align: middle;
`;

const IconSrcSetImg = styled(Image)`
  width: var(--icon-width, 16px);
  height: var(--icon-height, 16px);
`;

const IconSvg = styled(InlineSvg)`
  width: var(--icon-width, 16px);
  height: var(--icon-height, 16px);
  display: inline-block;

  svg {
    width: 100%;
    height: 100%;
    fill: var(--icon-color, currentColor);
  }
`;
