import { observer } from 'mobx-react-lite';
import { useCallback, useEffect } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { useModalContext } from '@/context/ModalContext';
import { DownloadIcon } from '@/icons';
import { getClipTitle } from '@/utils/clip';
import { downloadMedia, logDownloadToBilling } from '@/utils/download';
import { truncateText } from '@/utils/utils';

import Button, { ButtonVariant } from '../button/Button';
import SpinnerSVG from '../svg/SpinnerSVG';
import Modal from './Modal';
import { ModalTypes } from './constants/ModalTypes';

const DownloadWavModal = observer(() => {
  const { library, clips, session } = useStores();
  const { closeModal } = useModalContext();
  const clip = clips.pendingWavDownloadClip || clips.wavDownloadClip;

  const onClose = useCallback(() => {
    closeModal(ModalTypes.DOWNLOAD_FILE);
    clips.clearWavDownload();
  }, [closeModal, clips]);

  useEffect(() => {
    if (
      clips.pendingWavDownloadClip === null &&
      clips.wavDownloadClip === null
    ) {
      onClose();
    }
  }, [clips.pendingWavDownloadClip, clips.wavDownloadClip, onClose]);

  if (!clip) return null;

  return (
    <Modal
      title='Download WAV Audio'
      onClose={onClose}
      wrapperClasses='max-h-[480px] mb-4'
      withHorizontalPadding
    >
      <div className='my-4 flex w-full justify-center rounded-lg bg-background-secondary p-4'>
        <div
          className={`flex flex-row items-center ${clips.pendingWavDownloadClip ? '' : 'font-bold'}`}
        >
          {clips.pendingWavDownloadClip
            ? 'Preparing your download...'
            : `${truncateText(getClipTitle(clip))}.wav`}
        </div>
        <div className='flex flex-1 flex-row-reverse'>
          <Button
            className='py-4'
            variant={ButtonVariant.Secondary}
            onClick={async () => {
              if (clips.wavDownloadClip) {
                await downloadMedia(
                  library.apiClient,
                  clips.wavDownloadClip,
                  'audio-wav',
                  session,
                  clips.wavDownloadUrl || ''
                );
                logDownloadToBilling(library.apiClient, clip.id);
                onClose?.();
              }
            }}
            disabled={!!clips.pendingWavDownloadClip}
            icon={
              !!clips.pendingWavDownloadClip ? <SpinnerSVG /> : <DownloadIcon />
            }
          >
            Download File
          </Button>
        </div>
      </div>
    </Modal>
  );
});

export default DownloadWavModal;
