import React, { useCallback, useEffect, useState } from 'react';
import CircularProgress from '@mui/material/CircularProgress';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
import CancelIcon from '@mui/icons-material/Cancel';
import { getLabel } from '@reltio/mdm-sdk';
import { ExpandedValueTooltip } from '../ExpandedValueTooltip';
import { UploadMode } from './components/UploadMode';
import { showFileUploadError } from './helpers';
import { PROGRESS_ICON_SIZE, UploadState } from './constants';
import { useStyles } from './styles';
export var UploadFileButton = function (_a) {
    var link = _a.link, filename = _a.filename, onUpload = _a.onUpload, _b = _a.onError, onError = _b === void 0 ? showFileUploadError : _b, onCancel = _a.onCancel, supportedFileTypes = _a.supportedFileTypes, _c = _a.isValidLink, isValidLink = _c === void 0 ? true : _c;
    var _d = useState(UploadState.Init), mode = _d[0], setMode = _d[1];
    var _e = useState(''), name = _e[0], setName = _e[1];
    var styles = useStyles();
    useEffect(function () {
        setName(filename);
    }, [filename]);
    useEffect(function () {
        setMode(link ? UploadState.Uploaded : UploadState.Init);
    }, [link]);
    var onErrorHandler = useCallback(function (error) {
        setMode(UploadState.Init);
        onError(error);
    }, [onError]);
    var onUploadHandler = useCallback(function (result) {
        return onUpload(result)
            .then(function () {
            setMode(UploadState.Uploaded);
            setName(result.name);
        })
            .catch(onErrorHandler);
    }, [onUpload, onErrorHandler]);
    var onBeforeUpload = useCallback(function () {
        setMode(UploadState.Uploading);
    }, []);
    var switchToInitMode = useCallback(function () {
        setMode(UploadState.Init);
        onCancel();
    }, [onCancel]);
    switch (mode) {
        case UploadState.Init:
            return (React.createElement(UploadMode, { supportedFileTypes: supportedFileTypes, onUpload: onUploadHandler, onBeforeUpload: onBeforeUpload }));
        case UploadState.Uploaded: {
            var label = getLabel(name);
            return (React.createElement("div", { className: styles.uploaded },
                React.createElement(ExpandedValueTooltip, { value: label }, isValidLink ? (React.createElement(Link, { href: link, className: styles.label, underline: "hover" }, label)) : (React.createElement(Typography, { variant: "inherit", className: styles.label }, label))),
                React.createElement(CancelIcon, { onClick: switchToInitMode, onMouseDown: switchToInitMode, onTouchEnd: switchToInitMode, className: styles.cancelIcon })));
        }
        case UploadState.Uploading:
            return React.createElement(CircularProgress, { size: PROGRESS_ICON_SIZE });
        default:
            return null;
    }
};
