import { useCallback, useEffect, useRef } from 'react'
import { faEraser } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { MarkRenderSignature } from './Render'
import SignaturePad from 'signature_pad'
import { SIGNATURE_PAD_OPTIONS, SIGNATURE_PAD_SIZE } from '../../../utils/const'
import { BasicPoint } from 'signature_pad/dist/types/point'
import { MarkInputProps } from '../MarkStrategy'
import styles from './Input.module.scss'

export const MarkInputSignature = ({
  value,
  handler,
  userMark
}: MarkInputProps) => {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const signaturePad = useRef<SignaturePad | null>(null)

  const update = useCallback(() => {
    const data = signaturePad.current?.toData()
    const reduced = data?.map((pg) => pg.points)
    const json = JSON.stringify(reduced)

    if (signaturePad.current && !signaturePad.current?.isEmpty()) {
      handler(json)
    } else {
      handler('')
    }
  }, [handler])

  useEffect(() => {
    const handleEndStroke = () => {
      update()
    }
    if (canvasRef.current) {
      if (signaturePad.current === null) {
        signaturePad.current = new SignaturePad(
          canvasRef.current,
          SIGNATURE_PAD_OPTIONS
        )
      }

      signaturePad.current.addEventListener('endStroke', handleEndStroke)
    }

    return () => {
      window.removeEventListener('endStroke', handleEndStroke)
    }
  }, [update])

  useEffect(() => {
    if (signaturePad.current) {
      if (value) {
        signaturePad.current.fromData(
          JSON.parse(value).map((p: BasicPoint[]) => ({
            points: p
          }))
        )
      } else {
        signaturePad.current?.clear()
      }
    }
    update()
  }, [update, value])

  const handleReset = () => {
    signaturePad.current?.clear()
    update()
  }

  return (
    <div className={styles.wrapper}>
      <div
        className={styles.relative}
        style={{
          width: SIGNATURE_PAD_SIZE.width,
          height: SIGNATURE_PAD_SIZE.height
        }}
      >
        <canvas
          width={SIGNATURE_PAD_SIZE.width}
          height={SIGNATURE_PAD_SIZE.height}
          ref={canvasRef}
          className={styles.canvas}
        ></canvas>
        {typeof userMark?.mark !== 'undefined' && (
          <div className={styles.absolute}>
            <MarkRenderSignature
              key={userMark.mark.value}
              value={userMark.mark.value}
              mark={userMark.mark}
            />
          </div>
        )}
        <div className={styles.reset}>
          <FontAwesomeIcon size="sm" icon={faEraser} onClick={handleReset} />
        </div>
      </div>
    </div>
  )
}
