import React, { useEffect, useRef, useState } from 'react'
import { AnniveraryDateUtils } from '../AnniversaryDate/utils'

const defaultImg = require('../default-profile.png')
let idCounter = 0
const borderStyles = {
  normal: '0',
  rounded: '10',
  circle: '100'
}

interface Props {
  url: any
  size: number
  borderStyle: keyof typeof borderStyles
  orientation: any
}

export const AnniversaryImage: React.FunctionComponent<Props> = ({ url, size, borderStyle, orientation }) => {
  const [urlState, setUrlState] = useState(url || defaultImg)
  const input = useRef<SVGImageElement>(null)
  const maskId = `mask-${Date.now()}-${++idCounter}`
  const imageExist = (url: any) => {
    const isValidImage = url.substr(-3).toLowerCase() === 'png' || url.substr(-3).toLowerCase() === 'jpg' || url.substr(-4).toLowerCase() === 'jpeg'
    return isValidImage ? url : defaultImg
  }

  useEffect(() => {
    const urlImage = url && imageExist(url) || defaultImg
    setUrlState(urlImage)
    if (input.current !== null) {
      input.current.addEventListener('error', onError.bind(this))
    }
  }, [url])

  const onError = () => {
    console.log('Invalid image')
    setUrlState(defaultImg)
  }

  return (
    <svg viewBox='0 0 100 100' {...AnniveraryDateUtils.utils(orientation, size)}>
      <defs>
        <mask id={maskId} fill='#fff'>
          <rect width='100' height='100'
            rx={borderStyles[borderStyle] || '0'} />
        </mask>
      </defs>
      <image ref={input} style={{
        width: '100%',
        height: '100%'
      }} href={urlState} mask={`url(#${maskId})`} />
    </svg>
  )
}