import {ReactMediaRecorder} from "react-media-recorder";
import {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";

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

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

  const {t} = useTranslation('feedbackSupport')

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

  const options: MediaRecorderOptions = {};
  if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
    options.mimeType = 'video/webm; codecs=vp9';
  } else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
    options.mimeType = 'video/webm; codecs=vp8';
  } else if (MediaRecorder.isTypeSupported('video/mp4')) {
    options.mimeType = 'video/mp4';
  } else {
    throw Error('Recorder.error.unsupportedFormat')
  }


  const recorder = useMemo(() => {

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

      return 'gray'
    }
    return (
      <ReactMediaRecorder
        mediaRecorderOptions={options}
        screen
        video={{
          sampleRate: 20
        }}
        render={({status, startRecording, stopRecording, mediaBlobUrl}) => (
          <>
            <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(status)}
            >
              {t(`Recorder.status.${status}`)}
            </Badge>
          </>
        )}
        onStop={(blobUrl: string, blob: 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: options.mimeType
              })
            }
          pause()
        }}
        onStart={start}
      />
    )
  }, [])

  return (
    <Affix position={{bottom: 0}} style={{display: show ? 'block' : 'none', width: '100%', backgroundColor: '#aaa'}}>
      <Container>
        <Group position={"center"}>
          {recorder}
          <Badge
            color={'primary'}
          >
            {`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`}
          </Badge>
        </Group>
      </Container>
    </Affix>
  )
}