import React from 'react';
import styled from 'styled-components';
import { theme } from '@veeqo/ui';
import { EventHandlerProps } from 'types';

import { GlyphName, GlyphSize } from './types';
import glyphs from './glyphs';
import legacyIconMap from './legacyIconMap';

const { sizes } = theme;

/* eslint-disable-next-line max-len */
const isLatestGlyph = (glyphName: GlyphName): glyphName is keyof typeof glyphs => glyphName in glyphs;

export interface GlyphProps extends EventHandlerProps {
  name: GlyphName;
  color?: string;
  size?: GlyphSize;
  className?: string;
  ariaLabel?: string;
  style?: {
    [key: string]: string;
  };
}

type GlyphBaseProps = {
  color: string;
  size: string;
};

const GlyphBase = styled.div<GlyphBaseProps>`
  display: inline-block;
  color: ${({ color }) => color || 'inherit'};
  width: ${({ size }) => sizes[size]};
  height: ${({ size }) => sizes[size]};
  flex-shrink: 0;
`;

const Glyph = ({
  name,
  size = 'md',
  color,
  className,
  ariaLabel,
  style = {},
  onClick,
}: GlyphProps) => {
  const isLatest = isLatestGlyph(name);

  const GlyphComponent = isLatest
    ? (glyphs[name] || glyphs.placeholder)
    : legacyIconMap[name].Component;

  const glyphSize = isLatest ? size : (legacyIconMap[name].size || size);

  return (
    <GlyphBase
      as={GlyphComponent}
      className={className}
      role={ariaLabel ? 'img' : 'presentation'}
      aria-label={ariaLabel}
      onClick={onClick}
      style={style}
      size={glyphSize}
      color={color}
    />
  );
};

export default Glyph;
