import { useEffect, useState } from 'react';
import { Button, Flex } from '@chakra-ui/react';
import { AiOutlinePlayCircle, AiOutlinePauseCircle, AiOutlineStop } from 'react-icons/ai';
import { MdReplay } from 'react-icons/md';
import { BsRecordCircle } from 'react-icons/bs';
import propTypes from 'prop-types';

import { EVENT_NAMES } from '../../constants/define.js';
import AlertDialog from './AlertDialog.jsx';

const { RECORD, REPLAY, RESUME, PAUSE, ON_UPDATE_EVENT_LOG, ON_CLOSE_RECORDER, STOP } = EVENT_NAMES.CLIENT_RECORDER;
const { REMOVE_EVENT_LISTENER } = EVENT_NAMES.COMMON;

function Recorder({ value, name, onGetTargetUrl, onChange, disabled, isAllowRecord }) {
  const [isPaused, setIsPaused] = useState(false),
    [isRecording, setIsRecording] = useState(false);

  useEffect(() => {
    const updateEventLog = (_event, value) => {
      onChange({
        target: {
          name,
          value,
        },
      });
    };
    const closeRecorder = async () => {
      setIsRecording(false);
    };

    window.recorder[ON_UPDATE_EVENT_LOG](updateEventLog);
    window.recorder[ON_CLOSE_RECORDER](closeRecorder);

    return async () => {
      await Promise.all([
        window.common[REMOVE_EVENT_LISTENER](ON_UPDATE_EVENT_LOG, updateEventLog),
        window.common[REMOVE_EVENT_LISTENER](ON_CLOSE_RECORDER, closeRecorder),
        window.recorder[STOP](),
      ]);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleRecord = async () => {
    const targetUrl = onGetTargetUrl();
    onChange('');
    setIsRecording(true);
    await window?.recorder[RECORD](targetUrl);
  };

  const handleStopRecord = async () => {
    setIsRecording(false);
    await window?.recorder[STOP]();
  };

  const handleResumeRecord = async () => {
    setIsPaused(false);
    await window?.recorder[RESUME]();
  };

  const handlePauseRecord = async () => {
    setIsPaused(true);
    await window?.recorder[PAUSE]();
  };

  const handleReplay = async () => {
    console.log({ value });
    await window?.recorder[REPLAY](value);
  };

  return (
    <Flex gap={1}>
      {isRecording && !disabled ? (
        <>
          {isPaused ? (
            <Button onClick={handleResumeRecord} leftIcon={<AiOutlinePlayCircle />} bg="none">
              Resume
            </Button>
          ) : (
            <Button onClick={handlePauseRecord} leftIcon={<AiOutlinePauseCircle />} bg="none">
              Pause
            </Button>
          )}
          <Button onClick={handleStopRecord} leftIcon={<AiOutlineStop />} bg="none">
            Stop
          </Button>
        </>
      ) : (
        isAllowRecord && (
          <AlertDialog
            onConfirm={() => handleRecord()}
            title="Are you sure want to record?"
            body="The current Steps will lost if you continutely record"
            confirmButtonText="Record"
          >
            {(onOpenConfirmation) => (
              <Button disabled={disabled} onClick={onOpenConfirmation} leftIcon={<BsRecordCircle />} bg="none">
                Record
              </Button>
            )}
          </AlertDialog>
        )
      )}
      {value?.length > 0 && !disabled && (
        <Button leftIcon={<MdReplay />} onClick={handleReplay}>
          Replay
        </Button>
      )}
    </Flex>
  );
}

Recorder.propTypes = {
  onGetTargetUrl: propTypes.func.isRequired,
  onChange: propTypes.func,
  disabled: propTypes.bool,
};

Recorder.defaultProps = {
  actionCode: [],
  onChange: () => {},
  disabled: false,
  isAllowRecord: true,
};

export default Recorder;
