import {
  createRef,
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

import RecordingSheet from '../pages/ChannelPage/components/RecordingView';

export type RecordingSheetCallbacks = {
  onClose: () => void;
  onSend: (audio: Blob) => void;
};

export type RecordingSheetRefType = {
  open: (callbacks: RecordingSheetCallbacks) => void;
  close: () => void;
};

export const recordingSheetRef = createRef<RecordingSheetRefType>();

const RecordingSheetRoot = forwardRef<RecordingSheetRefType, {}>((_, ref) => {
  const [opened, setOpened] = useState(false);
  const callbacksRef = useRef<RecordingSheetCallbacks | null>(null);

  useImperativeHandle(ref, () => ({
    open: (callbacks: RecordingSheetCallbacks) => {
      callbacksRef.current = callbacks;
      setOpened(true);
    },
    close: () => {
      setOpened(false);
      callbacksRef.current = null;
    },
  }));

  if (!opened) return null;

  return (
    <RecordingSheet
      onCancel={() => {
        callbacksRef.current?.onClose();
        setOpened(false);
        callbacksRef.current = null;
      }}
      onSend={(blob) => {
        callbacksRef.current?.onSend(blob);
        setOpened(false);
        callbacksRef.current = null;
      }}
    />
  );
});

RecordingSheetRoot.displayName = 'RecordingSheetRoot';

export default RecordingSheetRoot;
