import {useEffect, useMemo, useState} from "react";
import {Affix, Badge, Button, Container, Group, Indicator} from "@mantine/core";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faPlay, faStop} from "@fortawesome/free-solid-svg-icons";
import {useTranslation} from "react-i18next";
import {useStopwatch} from "react-timer-hook";
// @ts-ignore
import Whammy from 'react-whammy'
import {toCanvas} from "html-to-image"

interface RecorderProps {
  show: boolean
  setRecord: (record: Record.Data) => void
}

export default function RecorderWhammy({
                                         show,
                                         setRecord
                                       }: RecorderProps) {

  const {t} = useTranslation('feedbackSupport')

  const [status, setStatus] = useState('idle')

  const [encoder, setEncoder] = useState<typeof Whammy>()

  const {
    seconds,
    minutes,
    start,
    pause
  } = useStopwatch({autoStart: false})

  useEffect(() => {
    var encoder = new Whammy.Video(1)
    setEncoder(encoder)
  }, [])

  useEffect(() => {
    if (status === 'recording') {
      toCanvas(document.body).then((canvas) => {
        encoder.add(canvas)
      })
    }
  }, [seconds])


  const startRecording = () => {
    setStatus('recording')
    start()
  }

  const stopRecording = () => {
    setStatus('compiling')
    pause()
    encoder.compile(false, (blob: Blob) => {

      const blobUrl = URL.createObjectURL(blob)

      var reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function () {
        var base64String = reader.result as string;

        setRecord({
          blobUrl: blobUrl,
          blob: blob,
          base64: base64String,
          mimeType: 'video/webm'
        })
      }
    })
  }

  const getStatusColor = () => {
    if (status === 'recording') {
      return 'red'
    }

    return 'gray'
  }


  return (
    <Affix position={{bottom: 0}} style={{display: show ? 'block' : 'none', width: '100%', backgroundColor: '#aaa'}}>
      <Container>
        <Group position={"center"}>
          <Indicator size={22} offset={5} color={status === 'recording' ? 'red' : 'gray'}
                     processing={status === 'recording' ? true : false}>
            <Button color={'green'} onClick={startRecording}><FontAwesomeIcon icon={faPlay}/></Button>
          </Indicator>
          <Button color={'red'} onClick={stopRecording}><FontAwesomeIcon icon={faStop}/></Button>
          <Badge
            color={getStatusColor()}
          >
            {t(`Recorder.status.${status}`)}
          </Badge>

          <Badge
            color={'primary'}
          >
            {`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`}
          </Badge>
        </Group>
      </Container>
    </Affix>
  )
}