import { useEffect, useState } from 'react'
import SignaturePad from 'signature_pad'
import { SIGNATURE_PAD_OPTIONS, SIGNATURE_PAD_SIZE } from '../../../utils'
import { BasicPoint } from 'signature_pad/dist/types/point'
import { MarkRenderProps } from '../MarkStrategy'
import styles from './Render.module.scss'

export const MarkRenderSignature = ({ value }: MarkRenderProps) => {
  const [dataUrl, setDataUrl] = useState<string | undefined>()

  useEffect(() => {
    if (value) {
      const canvas = document.createElement('canvas')
      canvas.width = SIGNATURE_PAD_SIZE.width
      canvas.height = SIGNATURE_PAD_SIZE.height
      const pad = new SignaturePad(canvas, SIGNATURE_PAD_OPTIONS)
      pad.fromData(
        JSON.parse(value).map((p: BasicPoint[]) => ({
          points: p
        }))
      )
      setDataUrl(canvas.toDataURL('image/webp'))
    }
  }, [value])

  return dataUrl ? <img src={dataUrl} className={styles.img} alt="" /> : null
}
