import React, { CSSProperties } from 'react'
import { browserCheck } from '@ta-interaktiv/browsercheck'
import { ReactSVG } from 'react-svg'
import { Errback } from '@tanem/svg-injector'
import { placeholderString, getAspectRatioPadding } from '../assets'
import './styles.scss'
// Image with Mobile-Desktop-Switch
export interface SVGProps {
  /** File to be displayed. Required file or array of two required files   */
  file?: string | [string, string]
  /** CSS-Class for the Image */
  className?: string
  /** Inline-Css for the Image */
  style?: CSSProperties
  /** Title to show above the Image */
  title?: string | JSX.Element
  /** Subtitle to show below title */
  sub?: string | JSX.Element
  /** Source to show below the image */
  source?: string | JSX.Element
  /** Proportions for the Image */
  aspectRatio?: string
  /** Specific height for the Image both |  [mobile,desktop] */
  height?: string | [string, string]
  /** Applies Css to let the image stick out of the text column */
  oversized?: boolean
  /** Child elements to be placed below subline and above image */
  children?: JSX.Element
  /** Places title and subline below image above source */
  imageFirst?: boolean
  /** any other properties get applied to the svg */
  props?: any // eslint-disable-line
  [key: string]: any // eslint-disable-line
}

interface CompFromStringProps {
  src: string
}
const CompFromString = ({ src }: CompFromStringProps) => {
  return (
    <div
      dangerouslySetInnerHTML={{
        __html: atob(src.replace(/data:image\/svg\+xml;base64,/, ''))
      }}
    />
  )
}
/** Displays an inline svg element. If two svg files have been provided one is rendered on desktop/tablets and one on mobile screens. Title, subtitle and source are displayed if provided.<br/> If no files are provided a placeholder is rendered.  */
export const InlineSvg = ({
  file,
  className,
  style,
  title,
  sub,
  source,
  height,
  aspectRatio,
  oversized,
  children,
  imageFirst,
  ...props
}: SVGProps) => {
  let src = ''
  let h = 'auto'

  if (file) {
    if (typeof file === 'object') {
      if (browserCheck.isMobile) {
        src = file[0].toString()
      } else {
        src = file[1].toString()
      }
    } else {
      src = file.toString()
    }
    if (!file.toString().includes('base64') && !file.toString().includes('/')) {
      src = 'images/' + src
    }
  }

  if (typeof height === 'object') {
    if (browserCheck.isMobile) {
      h = height[0]
    } else {
      h = height[1]
    }
  } else {
    h = height || '100%'
  }

  const ImgElement = ({ imageSrc }: { imageSrc?: string }) => {
    if (!imageSrc || imageSrc === '') {
      return (
        <img
          src={placeholderString}
          style={{
            ...{
              position: 'absolute',
              width: '100%',
              height: '100%'
            }
          }}
        />
      )
    }
    return (
      <img
        src={src}
        className='image'
        style={{
          ...style,
          ...(aspectRatio || height
            ? {
                position: 'absolute',
                top: '0',
                left: '0',
                right: '0',
                bottom: '0',
                height: '100%',
                width: '100%',
                objectFit: 'cover'
              }
            : { width: '100%' })
        }}
        {...props}
      />
    )
  }
  const doAfterInlineSVGInjection: Errback = (err, svg) => {
    if (svg) {
      if (
        svg &&
        svg.parentElement &&
        svg.parentElement.parentElement &&
        oversized
      ) {
        svg.parentElement.parentElement.removeAttribute('style')
      }
      svg.setAttribute('preserveAspectRatio', 'xMidYMid slice')
      if (h || aspectRatio) {
        svg.setAttribute('width', '100%')
        svg.setAttribute('height', h)
      }
    }
    if (err) {
      console.warn('contentbricks | SVG \n', err)
    }
  }

  if (src === '' && !height && !aspectRatio) aspectRatio = '16:9'

  const titleElement = <div className='title'>{title}</div>
  const subElement = <div className='sub'>{sub}</div>
  const sourceElement = <div className='source'>{source}</div>

  return (
    <div className={className + ' ' + (oversized ? 'oversized' : '')}>
      <figure>
        {!imageFirst && (
          <figcaption>
            {title && titleElement}
            {sub && subElement}
          </figcaption>
        )}
        {children && !imageFirst && children}
        {src.includes('data:image/svg+xml;base64,') ? (
          <CompFromString src={src} />
        ) : (
          <ReactSVG
            src={src}
            className={
              height || aspectRatio ? 'image svgContainer' : 'svgContainer'
            }
            wrapper='div'
            {...props}
            style={{
              ...style,
              ...(aspectRatio || height
                ? {
                    position: 'relative',
                    top: '0',
                    left: '0',
                    right: '0',
                    bottom: '0',
                    height: h || '100%',
                    width: '100%',
                    objectFit: 'cover',
                    paddingBottom: aspectRatio
                      ? getAspectRatioPadding(aspectRatio)
                      : '0'
                  }
                : { width: '100%' })
            }}
            afterInjection={doAfterInlineSVGInjection}
            fallback={() => <ImgElement imageSrc={src} />}
          />
        )}
        {children && imageFirst && children}

        {imageFirst && (
          <figcaption>
            {title && titleElement}
            {sub && subElement}
            {source && sourceElement}
          </figcaption>
        )}
        {source && !imageFirst && sourceElement}
      </figure>
    </div>
  )
}
InlineSvg.defaultProps = {
  className: 'cbSVG',
  oversized: false
}
