import React, { useState, useEffect, useImperativeHandle, useMemo, useCallback } from 'react';
import { AmbientAlert, Divider, EmptyStateDisplay, FileViewer, LinearProgress } from '../../../../UI';
import AttachmentTransactionAttachmentList from '../components/AttachmentTransactionAttachmentList';
import { apiMutate } from '../../../../utilities';
import { ViewIcon } from '@fluentui/react-icons';
import { makeStyles } from '@material-ui/core';
import { useAxiosGet } from '../../../../utilities';
import { useTranslation } from 'react-i18next';
import { ConfigService } from '../../../../configService';
const AttachmentTransaction = (props) => {
    const { transaction, attachmentRef } = props;
    const [selectedAttachment, setSelectedAttachment] = useState('');
    const attachments = (transaction === null || transaction === void 0 ? void 0 : transaction.udpTransactionUdpTransactionAttachment) || [];
    const { t } = useTranslation();
    const [{ data: attachmentFileInfo }, refetchattachmentFileInfo] = useAxiosGet(`${ConfigService.productV1ApiUrl}`, `UdpTransactionAttachment/${selectedAttachment === null || selectedAttachment === void 0 ? void 0 : selectedAttachment.transactionAttachmentId}/udpDriveFile/download`, {}, true);
    const [{ data: attachmentFile, loading: loadingFile, error: downloadError }, refetchAttachmentFile] = useAxiosGet(`${ConfigService.productV1ApiUrl}`, `UdpTransactionAttachment/${selectedAttachment === null || selectedAttachment === void 0 ? void 0 : selectedAttachment.transactionAttachmentId}/download`, {
        responseType: 'blob'
    }, true);
    const blobUrl = useMemo(() => {
        if (!attachmentFile)
            return null;
        const pdfBlob = new Blob([attachmentFile], { type: 'application/pdf' });
        return URL.createObjectURL(pdfBlob);
    }, [attachmentFile]);
    useEffect(() => {
        if (selectedAttachment) {
            refetchattachmentFileInfo();
            refetchAttachmentFile();
        }
    }, [selectedAttachment, refetchattachmentFileInfo, refetchAttachmentFile]);
    const getErrorMessage = () => {
        var _a;
        if (!downloadError)
            return null;
        const status = (_a = downloadError.response) === null || _a === void 0 ? void 0 : _a.status;
        if (status === 404)
            return t('The requested attachment could not be found.');
        if (status >= 500)
            return t('A server error occured. Please try again later.');
        return downloadError.message || t('An unexpected error occured.');
    };
    let fileDataObj = {
        filePath: blobUrl,
        fileExtension: attachmentFileInfo === null || attachmentFileInfo === void 0 ? void 0 : attachmentFileInfo.extension
    };
    const fixedHeight = 'calc(100vh - 140px)';
    const useStyles = makeStyles((theme) => ({
        sidesheet: {
            display: 'flex',
            flexDirection: 'row',
            flex: 1,
            height: fixedHeight
        },
        attachmentListContainer: {
            textAlign: 'left',
            width: '35%',
            height: fixedHeight
        },
        attachmentListHeader: {
            backgroundColor: 'white',
            justifyItems: 'left',
            paddingLeft: '5%'
        },
        attachmentListHeaderPrimaryText: {
            fontSize: 'var(--h6-font-size)',
            fontWeight: 'var(--body1-font-weight)',
            color: 'var(--text-main)'
        },
        attachmentListHeaderSecondaryText: {
            fontSize: 'var(--body2-font-size)',
            color: 'var(--text-secondary)',
            paddingBottom: '2%'
        },
        attachemntFileInfoCol: {
            width: '50%',
            display: 'flex',
            flexDirection: 'column',
            flex: 1,
            overflowY: 'auto',
            height: 'calc(100vh - 50px)'
        },
        attachmentFileNameHeader: {
            backgroundColor: 'white'
        },
        attachmentFileName: {
            color: 'var(--text-main)',
            fontSize: 'var(--h6-font-size)',
            fontWeight: 'var(--body1-font-weight)',
            marginTop: '1%',
            marginBottom: '1%',
            justifySelf: 'center'
        },
        fileViewer: {
            marginLeft: 'var(--spacing-02)',
            marginRight: 'var(--spacing-02)'
        },
        divider: {
            '& MuiDivider-root': {
                backgroundColor: 'var(--gray-02)'
            }
        }
    }));
    const classStyles = useStyles();
    useImperativeHandle(attachmentRef, () => ({
        downloadSelectedFile: async () => {
            var _a;
            if (!selectedAttachment)
                return;
            try {
                const response = await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/${selectedAttachment.transactionAttachmentId}/udpDriveFile/download`, {});
                const url = response.data.link;
                const link = document.createElement('a');
                link.href = url;
                link.download = (_a = selectedAttachment.fileName) !== null && _a !== void 0 ? _a : selectedAttachment.name;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
            catch (e) {
                console.error('Download failed', e);
            }
        }
    }));
    const handleOpenInNewTab = useCallback((e) => {
        e === null || e === void 0 ? void 0 : e.preventDefault();
        if (blobUrl) {
            window.open(blobUrl, '_blank');
        }
    }, [blobUrl]);
    const refetchAttachment = () => {
        refetchattachmentFileInfo();
        refetchAttachmentFile();
    };
    return (React.createElement(React.Fragment, null, React.createElement("div", { className: classStyles.sidesheet }, React.createElement("div", { className: classStyles.attachmentListContainer }, React.createElement("div", { className: classStyles.attachmentListHeader }, React.createElement("div", { className: classStyles.attachmentListHeaderPrimaryText }, "Attachment"), React.createElement("div", { className: classStyles.attachmentListHeaderSecondaryText }, (attachments === null || attachments === void 0 ? void 0 : attachments.length) + ' file(s) attached')), React.createElement("div", { className: classStyles.divider }, React.createElement(Divider, null)), React.createElement(AttachmentTransactionAttachmentList, { transaction: transaction, attachments: attachments, setSelectedAttachment: setSelectedAttachment })), React.createElement("div", { className: classStyles.attachemntFileInfoCol }, React.createElement("div", { className: classStyles.attachmentFileNameHeader }, selectedAttachment && (React.createElement("p", { className: classStyles.attachmentFileName }, selectedAttachment.attachmentName)), React.createElement("div", { className: classStyles.divider }, React.createElement(Divider, null))), downloadError && (React.createElement(AmbientAlert, { showAlert: !!downloadError, alertSeverity: 'error', alertTitle: t('Failed to load preview'), alertMessage: getErrorMessage(), alertAction: true, alertActionButton: t('Retry'), alertHandleAction: () => refetchAttachment() })), loadingFile && !downloadError ? (React.createElement(LinearProgress, null)) : selectedAttachment && attachmentFileInfo && blobUrl ? (React.createElement("div", { className: classStyles.fileViewer }, React.createElement(FileViewer, { data: (attachmentFileInfo === null || attachmentFileInfo === void 0 ? void 0 : attachmentFileInfo.extension) == 'pdf'
            ? fileDataObj
            : [fileDataObj], onClickDownload: handleOpenInNewTab }))) : (!selectedAttachment && (React.createElement(EmptyStateDisplay, { icon: ViewIcon, primaryText: 'Select an attachment to preview', secondaryText: 'Choose a file from the attachments list to view its contents' })))))));
};
export default AttachmentTransaction;
//# sourceMappingURL=AttachmentTransaction.js.map