import React from 'react';
import lodash from 'lodash';
import DropboxIcon from 'src/assets/svg/dropbox-icon.svg';
import { ASSET_FILETYPES, DROPBOX_DROPINS_JS_URL } from 'src/constants';
import loadScripts from 'src/utils/load-scripts';

interface SelectFileFromDropboxProps {
    onUploadFile: (acceptedFiles: File[]) => void;
}

const SelectFileFromDropbox = (props: SelectFileFromDropboxProps) => {
    const { onUploadFile } = props;

    const DROPBOX_APP_KEY = process.env.DROPBOX_APP_KEY ?? '';

    const loadDropboxDropinsJs = lodash.once(
        async () =>
            await loadScripts([
                {
                    src: DROPBOX_DROPINS_JS_URL,
                    id: 'dropboxjs',
                    'data-app-key': DROPBOX_APP_KEY,
                },
            ])
    );

    const showChooser = () => () =>
        window.Dropbox.choose({
            success: () => {
                onUploadFile([new File([], 'placeholder')]);
            },
            linkType: 'direct',
            multiselect: false,
            extensions: ASSET_FILETYPES,
            folderselect: false,
        });

    return (
        <div
            className="select-file-from-third-party"
            onClick={async event => {
                event.stopPropagation();
                return await loadDropboxDropinsJs().then(showChooser());
            }}
        >
            <div className="select-file-from-third-party-icon">
                <img src={String(DropboxIcon)} alt="dropbox" />
            </div>
            <label className="select-file-from-third-party-label">
                DROPBOX
            </label>
        </div>
    );
};

export default SelectFileFromDropbox;
