import React, { useState, useRef, useCallback, useMemo, useEffect } from 'react';
import { Divider, SideSheet, UdpTabPanel } from '../../../../UI';
import { UdpTabs } from '../../../../UI/navigation/tabs/UdpTabs';
import { useTranslation } from 'react-i18next';
import { allowedExtensions, MAX_FILE_SIZE_MB } from '../../../../uploader/utils/allowedFileProperties';
import './EditTransaction.css';
import EditTransactionHeaderItem from './EditTransactionHeaderItem';
import { FluentButton } from '../../../../UI/inputs/buttons';
import WorkflowActions from './WorkflowActions';
import { TransactionTimeline } from '../components/transactionHistory/TransactionTimeline';
import { TransactionAttachments } from '../components/transactionAttachment/TransactionAttachments';
import { TransactionNotes } from '../components/transactionNote/TransactionNotes';
import { TRANSACTION_TAB } from './enum';
import { TransactionUiActionTypeEnums } from '../../../../enums';
import UdpTransactionCustomPage from '../components/UdpTransactionCustomPage';
import EditTransactionDetailsFooterItem from '../components/EditTransactionDetailsFooterItem';
import { ConfigService } from '../../../../configService';
import { useTransactionEngine } from '../../../../utilities/transactions/useTransactionEngine';
import DynamicTransactionDomainForm from '../components/DynamicTransactionDomainForm';
import { Attachments } from '../../../../uploader';
import { apiMutate, useAxiosGet, useAxiosMutate } from '../../../../utilities';
import { useSnackbar } from 'notistack';
import { TransactionNoteForm } from '../components/transactionNote/TransactionNoteForm';
import { FluentIcon } from '../../../../utilities/iconLibrary';
import { AddIcon } from '@fluentui/react-icons';
const EditTransaction = (props) => {
    const { transaction: initialTransaction, transactionTypeId, transactionIsClosed, openInnerSidesheetState, setOpenInnerSidesheetState, refreshGridData, closeSideSheet, setSidesheetLoading, setHasUnsavedChanges, domainName, attachmentType, setAttachmentType, currentAttachments, setCurrentAttachments, attachmentProgress, setAttachmentProgress, transactionAttachmentTypes, transactionAttachments, setTransactionAttachments, filePreview, setFilePreview, additionalPageParms, hideSaveChanges, catalogObject } = props;
    const { t } = useTranslation();
    const [selectedTab, setSelectedTab] = useState(0);
    const [transaction, setTransaction] = useState(initialTransaction);
    const [refreshNotes, setRefreshNotes] = useState(false);
    const [{ data: noteTypes, loading: fetchNoteTypesLoading }] = useAxiosGet(ConfigService.productV1ApiUrl, `UdpNoteType`, {});
    const { getUiActionRenderParameters, transactionTypeStatusColorsMap } = useTransactionEngine(transactionTypeId);
    const refetchTransaction = useCallback(async () => {
        var _a;
        setSidesheetLoading(true);
        const response = await apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${initialTransaction === null || initialTransaction === void 0 ? void 0 : initialTransaction.transactionId}/full`, {
            method: 'get'
        });
        if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
            setTransaction(response.data);
            (_a = transactionTimelineRef.current) === null || _a === void 0 ? void 0 : _a.refresh();
        }
        setSidesheetLoading(false);
    }, [initialTransaction === null || initialTransaction === void 0 ? void 0 : initialTransaction.transactionId, setSidesheetLoading]);
    const formRef = useRef(null);
    const transactionNoteFormRef = useRef(null);
    const transactionTimelineRef = useRef();
    const handleNoteFormSubmit = useCallback(() => {
        var _a, _b;
        (_b = (_a = transactionNoteFormRef.current) === null || _a === void 0 ? void 0 : _a.handleSubmit) === null || _b === void 0 ? void 0 : _b.call(_a);
    }, []);
    const handleNoteFormReset = useCallback(() => {
        var _a, _b, _c;
        (_c = (_b = (_a = transactionNoteFormRef.current) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.reset) === null || _c === void 0 ? void 0 : _c.call(_b);
    }, []);
    const handleSaveSuccess = useCallback((response) => {
        refreshGridData();
    }, [refreshGridData]);
    const handleSaveChanges = useCallback(async () => {
        var _a, _b;
        setSidesheetLoading(true);
        await ((_b = (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.submit());
        setSidesheetLoading(false);
    }, [setSidesheetLoading, formRef]);
    const [{ data: transactionAttachmentsData, loading: fetchTransactionAttachmentsLoading }, fetchTransactionAttachments] = useAxiosMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/search`, {
        method: 'post',
        data: {
            pageSize: 50,
            filterElements: [
                {
                    searchField: 'TransactionId',
                    searchValue: transaction.transactionId,
                    searchOperator: '='
                },
                {
                    searchField: 'IsDeleted',
                    searchValue: 0,
                    searchOperator: '='
                }
            ]
        }
    });
    const { enqueueSnackbar } = useSnackbar();
    const getAttachments = useCallback(async () => {
        try {
            const response = await fetchTransactionAttachments();
            setTransactionAttachments(response.data.pageList);
            refetchTransaction();
        }
        catch (error) {
            console.error('Failed to fetch attachments:', error);
            if ((error === null || error === void 0 ? void 0 : error.message) !== 'canceled') {
                enqueueSnackbar('Attachment fetch failed: We encountered a system error. Please try again or contact support if the issue persists.', {
                    variant: 'error',
                    anchorOrigin: { vertical: 'top', horizontal: 'center' }
                });
            }
        }
    }, [
        fetchTransactionAttachments,
        enqueueSnackbar,
        refetchTransaction,
        setTransactionAttachments
    ]);
    const tabNames = [t('Details'), t('History'), t('Attachments'), t('Notes')];
    const headerItemInfo = useMemo(() => {
        var _a, _b;
        const items = [
            {
                label: 'Status',
                statusChip: {
                    label: (_a = transaction.udpTransactionUdpTransactionTypeStatus) === null || _a === void 0 ? void 0 : _a.name,
                    status: transactionTypeStatusColorsMap[(_b = transaction.udpTransactionUdpTransactionTypeStatus) === null || _b === void 0 ? void 0 : _b.name] || 'default'
                }
            }
        ];
        if (transaction === null || transaction === void 0 ? void 0 : transaction.currentRevisionNo) {
            items.push({
                label: 'Revision',
                value: `${transaction.currentRevisionNo}`
            });
        }
        return items;
    }, [transaction, transactionTypeStatusColorsMap]);
    const handleUploadFiles = useCallback(async () => {
        if (!currentAttachments.length) {
            throw new Error('No files added for upload');
        }
        const formData = new FormData();
        currentAttachments.forEach((file) => formData.append('files', file));
        formData.append('attachmentTypeId', attachmentType.transactionAttachmentTypeId);
        try {
            setAttachmentProgress(true);
            await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/transaction/${transaction.transactionId}/upload`, {
                method: 'post',
                headers: {
                    transactionId: transaction.transactionId,
                    attachmentTypeId: attachmentType.transactionAttachmentTypeId
                },
                data: formData
            });
            await getAttachments();
            setCurrentAttachments([]);
            setOpenInnerSidesheetState({ attachments: false });
            enqueueSnackbar('Files uploaded successfully', {
                variant: 'success',
                anchorOrigin: {
                    vertical: 'top',
                    horizontal: 'center'
                }
            });
        }
        catch (error) {
            enqueueSnackbar(`File upload failed: We encountered a system error. Please try again or contact support if the issue persists.`, {
                variant: 'error',
                anchorOrigin: {
                    vertical: 'top',
                    horizontal: 'center'
                }
            });
            throw error;
        }
        finally {
            setAttachmentProgress(false);
        }
    }, [
        attachmentType,
        currentAttachments,
        enqueueSnackbar,
        getAttachments,
        setOpenInnerSidesheetState,
        transaction.transactionId,
        setCurrentAttachments,
        setAttachmentProgress
    ]);
    const innerSidesheetList = useMemo(() => [
        {
            open: openInnerSidesheetState.workflowAction,
            closeSheet: () => setOpenInnerSidesheetState({ workflowActions: false }),
            title: 'Available Workflow Actions',
            children: (React.createElement(WorkflowActions, { transaction: transaction, closeSideSheet: () => {
                    setOpenInnerSidesheetState({
                        workflowActions: false
                    });
                    refetchTransaction();
                }, refreshGridData: refreshGridData }))
        },
        {
            open: openInnerSidesheetState.attachments,
            closeSheet: () => setOpenInnerSidesheetState({ attachments: false }),
            title: 'Add Attachment',
            buttonLabel: 'Save',
            buttonOneDisabled: !attachmentType || currentAttachments.length <= 0,
            onSubmit: () => {
                handleUploadFiles()
                    .then(() => refreshGridData())
                    .catch((error) => console.error(error));
            },
            children: (React.createElement(Attachments, { attachmentTypes: transactionAttachmentTypes, attachmentType: attachmentType, setAttachmentType: setAttachmentType, attachmentProgress: attachmentProgress, setAttachmentProgress: setAttachmentProgress, currentAttachments: currentAttachments, setCurrentAttachments: setCurrentAttachments, transaction: transaction, previousAttachments: transactionAttachments, setPreviousAttachments: setTransactionAttachments, MAX_FILE_SIZE_MB: MAX_FILE_SIZE_MB, allowedExtensions: allowedExtensions, filePreview: filePreview, setFilePreview: setFilePreview }))
        },
        {
            open: openInnerSidesheetState.notes,
            closeSheet: () => setOpenInnerSidesheetState({ notes: false }),
            title: 'Add Note',
            buttonLabel: 'Save note',
            buttonTwoLabel: 'Clear',
            buttonTwoAction: handleNoteFormReset,
            onSubmit: handleNoteFormSubmit,
            children: (React.createElement(TransactionNoteForm, { ref: transactionNoteFormRef, businessObjectKey: transaction === null || transaction === void 0 ? void 0 : transaction.businessObjectKey, closeSideSheet: () => {
                    setOpenInnerSidesheetState({ notes: false });
                    setRefreshNotes(true);
                }, noteTypes: noteTypes, fetchNoteTypesLoading: fetchNoteTypesLoading }))
        }
    ], [
        openInnerSidesheetState.workflowAction,
        openInnerSidesheetState.attachments,
        openInnerSidesheetState.notes,
        transaction,
        refreshGridData,
        attachmentType,
        currentAttachments,
        transactionAttachmentTypes,
        attachmentProgress,
        transactionAttachments,
        filePreview,
        handleNoteFormReset,
        handleNoteFormSubmit,
        noteTypes,
        fetchNoteTypesLoading,
        setOpenInnerSidesheetState,
        refetchTransaction,
        handleUploadFiles,
        setAttachmentType,
        setCurrentAttachments,
        setAttachmentProgress,
        setTransactionAttachments,
        setFilePreview
    ]);
    const transactionDetailPageId = useMemo(() => {
        var _a;
        return (_a = getUiActionRenderParameters(TransactionUiActionTypeEnums.Render_Transaction_Details_Page)) === null || _a === void 0 ? void 0 : _a.pageId;
    }, [getUiActionRenderParameters]);
    useEffect(() => {
        (async () => {
            if (!transactionAttachmentsData) {
                getAttachments();
            }
        })();
    }, [transactionAttachmentsData, getAttachments]);
    return (React.createElement(React.Fragment, null, React.createElement("div", { className: "edit-transaction-sidesheet" }, React.createElement("div", { className: `edit-transaction-sidesheet-header 'is-sticky'` }, React.createElement("div", { className: "edit-transaction-sidesheet-header-title" }), React.createElement("div", { className: "edit-transaction-sidesheet-header-content" }, React.createElement("div", { className: "edit-transaction-sidesheet-header-items" }, headerItemInfo.map((headerItem) => {
        return (React.createElement(EditTransactionHeaderItem, { key: headerItem.label, label: headerItem.label, statusChip: headerItem.statusChip, value: headerItem.value }));
    })), React.createElement("div", { className: "edit-transaction-sidesheet-header-buttons" }, React.createElement(FluentButton, { color: "primary", onClick: () => {
            setOpenInnerSidesheetState({ attachments: true });
        } }, React.createElement(FluentIcon, { component: AddIcon, className: "edit-transaction-header-button-icon", size: "small" }), 'Attachment'), React.createElement(FluentButton, { color: "primary", onClick: () => {
            setOpenInnerSidesheetState({ notes: true });
        } }, React.createElement(FluentIcon, { component: AddIcon, className: "edit-transaction-header-button-icon", size: "small" }), 'Note')), React.createElement("div", { className: "divider" }, React.createElement(Divider, null)), React.createElement("div", { className: "edit-transaction-sidesheet-tabs" }, React.createElement(UdpTabs, { value: selectedTab, onChange: (value, tabIndex) => {
            setSelectedTab(tabIndex);
        }, tabList: tabNames.map((tabName) => ({ label: tabName })), buttonWidth: '100%' }))), React.createElement("div", { className: "divider" }, React.createElement(Divider, null))), React.createElement("div", { className: "edit-transaction-sidesheet-body" }, React.createElement("div", null, React.createElement(UdpTabPanel, { value: selectedTab, index: TRANSACTION_TAB.DETAILS }, transactionDetailPageId ? (React.createElement(UdpTransactionCustomPage, { transactionTypeId: transactionTypeId, transactionUiActionType: TransactionUiActionTypeEnums.Render_Transaction_Details_Page, formRef: formRef, transaction: transaction, refetchTransaction: refetchTransaction, setHasUnsavedChanges: setHasUnsavedChanges, refreshGridData: refreshGridData, additionalPageParms: additionalPageParms, onSubmitSuccess: handleSaveSuccess })) : (React.createElement(DynamicTransactionDomainForm, { transaction: transaction, formRef: formRef, domainName: domainName, transactionTypeId: transactionTypeId, transactionUiActionType: TransactionUiActionTypeEnums.Render_Transaction_Details_Page, setHasUnsavedChanges: setHasUnsavedChanges, refetchTransaction: refetchTransaction, onSubmitSuccess: handleSaveSuccess, catalogObject: catalogObject }))), React.createElement(UdpTabPanel, { value: selectedTab, index: TRANSACTION_TAB.HISTORY }, React.createElement(TransactionTimeline, { ref: transactionTimelineRef, transactionId: transaction === null || transaction === void 0 ? void 0 : transaction.transactionId })), React.createElement(UdpTabPanel, { value: selectedTab, index: TRANSACTION_TAB.ATTACHMENTS }, React.createElement(TransactionAttachments, { transactionAttachments: transactionAttachmentsData, isLoading: fetchTransactionAttachmentsLoading })), React.createElement(UdpTabPanel, { value: selectedTab, index: TRANSACTION_TAB.NOTES }, React.createElement(TransactionNotes, { businessObjectKey: transaction === null || transaction === void 0 ? void 0 : transaction.businessObjectKey, refreshNotes: refreshNotes, setRefreshNotes: setRefreshNotes, noteTypes: noteTypes, fetchNoteTypeLoading: fetchNoteTypesLoading })))), selectedTab == TRANSACTION_TAB.DETAILS && (React.createElement("div", { className: "edit-transaction-sidesheet-footer" }, React.createElement(EditTransactionDetailsFooterItem, { transactionTypeId: transactionTypeId, transactionIsClosed: transactionIsClosed, handleOnCancel: closeSideSheet, handleOnSaveChanges: handleSaveChanges, hideSaveChanges: hideSaveChanges })))), openInnerSidesheetState &&
        // eslint-disable-next-line react-hooks/refs
        innerSidesheetList.map((item) => {
            return (React.createElement(SideSheet, { key: item.title, open: item.open, width: 600, title: item.title, onClose: item.closeSheet, buttonLabel: item === null || item === void 0 ? void 0 : item.buttonLabel, buttonOneDisabled: item === null || item === void 0 ? void 0 : item.buttonOneDisabled, buttonTwoLabel: item === null || item === void 0 ? void 0 : item.buttonTwoLabel, buttonTwoAction: item === null || item === void 0 ? void 0 : item.buttonTwoAction, onSubmit: item === null || item === void 0 ? void 0 : item.onSubmit, color: "primary" }, item.children));
        })));
};
export default EditTransaction;
//# sourceMappingURL=EditTransaction.js.map