import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from 'react';
import { useMutation } from 'react-query';
import { useNavigate } from 'react-router';
import { useTheme } from 'styled-components';
import { Icon, LargerText, Modal, SecondaryText, Stack, Wrap } from '../..';
import { Table } from '../../components/tablev2/Tablev2.component';
import { Box, Button } from '../../next';
import { AttachmentAction } from './AttachmentTypes';
//The entity is the "thing" you want to attach to the resource, sorry about the naming :(
export function AttachmentConfirmationModal({ attachmentOperations, getAttachmentMutationOptions, resourceType, resourceName, redirectUrl, EntityIcon, cancelButtonDisabled, onCancel, onExit, }) {
    const navigate = useNavigate();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleClose = () => {
        setIsModalOpen(false);
    };
    const [attachmentOperationsStatuses, setAttachmentOperationsStatuses] = useState({});
    const attachmentMutation = useMutation({
        ...getAttachmentMutationOptions(),
        onSettled: (_, error, flatEntity) => {
            setAttachmentOperationsStatuses((statuses) => ({
                ...statuses,
                [flatEntity.id]: error ? 'Error' : 'Success',
            }));
        },
    });
    const attachmentOperationsFlat = attachmentOperations.map((attachmentOperation) => {
        return {
            action: attachmentOperation.action,
            type: attachmentOperation.entity.type,
            entityName: attachmentOperation.entity.name,
            id: attachmentOperation.entity.id,
            completeEntity: attachmentOperation.entity.completeEntity,
        };
    });
    const attach = () => {
        attachmentOperationsFlat.forEach((attachmentOperationFlat) => {
            if (attachmentOperationsStatuses[attachmentOperationFlat.id] ===
                'Waiting for confirmation' ||
                attachmentOperationsStatuses[attachmentOperationFlat.id] === 'Error' ||
                !attachmentOperationsStatuses[attachmentOperationFlat.id]) {
                setAttachmentOperationsStatuses((attachmentOperationsStatuses) => {
                    return {
                        ...attachmentOperationsStatuses,
                        [attachmentOperationFlat.id]: 'Waiting for confirmation',
                    };
                });
                attachmentMutation.mutate({
                    ...attachmentOperationFlat,
                });
            }
        });
    };
    const isAttachNotDone = attachmentOperationsFlat.find((attachmentOperation) => !attachmentOperationsStatuses[attachmentOperation.id]);
    const handleExit = () => {
        if (onExit) {
            const successfulOperations = Object.entries(attachmentOperationsStatuses)
                .filter(([_, status]) => status === 'Success')
                .flatMap(([operationId]) => {
                const op = attachmentOperations.find((op) => op.entity.id === operationId);
                if (op)
                    return [op];
                return [];
            });
            const failedOperations = Object.entries(attachmentOperationsStatuses)
                .filter(([_, status]) => status === 'Error')
                .flatMap(([operationId]) => {
                const op = attachmentOperations.find((op) => op.entity.id === operationId);
                if (op)
                    return [op];
                return [];
            });
            onExit(successfulOperations, failedOperations);
        }
        handleClose();
        navigate(redirectUrl);
    };
    const modalFooter = () => {
        return (_jsxs(Wrap, { children: [_jsx("p", {}), _jsx(_Fragment, { children: isAttachNotDone ? (_jsxs(Stack, { children: [_jsx(Button, { variant: "outline", onClick: handleClose, label: "Cancel" }), _jsx(Button, { icon: _jsx(Icon, { name: "Arrow-right" }), variant: "primary", onClick: attach, label: "Confirm", disabled: attachmentMutation.isLoading })] })) : (_jsx(Button, { icon: _jsx(Icon, { name: "Arrow-right" }), variant: "primary", onClick: () => {
                            handleExit();
                        }, label: "Exit" })) })] }));
    };
    function AttachmentList() {
        const theme = useTheme();
        const columns = [
            {
                Header: 'Action',
                accessor: 'action',
                cellStyle: {
                    width: '12.5%',
                },
                Cell: ({ value }) => {
                    return value === AttachmentAction.ADD ? (_jsxs("span", { children: [_jsx(Icon, { name: "Link" }), " Attach"] })) : (_jsxs(Box, { color: theme.statusCritical, children: [_jsx(Icon, { name: "Unlink" }), " Detach"] }));
                },
            },
            {
                Header: 'Type',
                accessor: 'type',
                cellStyle: {
                    width: '12.5%',
                },
                Cell: ({ value }) => {
                    return _jsx(EntityIcon, { type: value });
                },
            },
            {
                Header: 'Entity name',
                accessor: 'entityName',
                cellStyle: {
                    width: '42.5%',
                },
            },
            {
                Header: 'Attachment status',
                accessor: 'id',
                cellStyle: {
                    width: '32.5%',
                },
                Cell: ({ value: resourceId }) => {
                    if (attachmentOperationsStatuses[resourceId] === 'Error') {
                        return (_jsxs(Box, { display: "flex", gap: 8, alignItems: "center", children: [_jsx(Icon, { color: "statusCritical", name: "Times-circle" }), attachmentOperationsStatuses[resourceId], ' ', _jsx(Button, { size: "inline", onClick: attach, variant: "outline", label: "Retry" })] }));
                    }
                    if (attachmentOperationsStatuses[resourceId] === 'Success') {
                        return (_jsxs(Box, { display: "flex", gap: 8, alignItems: "center", children: [_jsx(Icon, { color: "statusHealthy", name: "Check-circle" }), attachmentOperationsStatuses[resourceId]] }));
                    }
                    return (_jsx(_Fragment, { children: attachmentOperationsStatuses[resourceId] ||
                            'Waiting for confirmation' }));
                },
            },
        ];
        return (_jsxs("div", { style: { height: '25rem', width: '50rem' }, children: [_jsx("div", { children: "The following entities will be attached or detached: " }), _jsxs(Box, { display: "flex", gap: 24, alignItems: "center", children: [_jsx(SecondaryText, { children: _jsx(EntityIcon, { type: resourceType }) }), _jsx("p", { children: resourceName })] }), _jsx(Table, { columns: columns, data: attachmentOperationsFlat, defaultSortingKey: 'entityName', children: _jsx(Table.SingleSelectableContent, { rowHeight: "h32", separationLineVariant: "backgroundLevel3", children: (Rows) => {
                            return _jsx(_Fragment, { children: Rows });
                        } }) })] }));
    }
    return (_jsxs(_Fragment, { children: [_jsx(Button, { label: "Cancel", variant: "outline", disabled: cancelButtonDisabled, onClick: () => {
                    if (onCancel)
                        onCancel();
                    navigate(redirectUrl);
                } }), _jsx(Button, { icon: _jsx(Icon, { name: "Save" }), label: "Save", onClick: () => {
                    setAttachmentOperationsStatuses({});
                    setIsModalOpen(true);
                }, variant: "primary", disabled: attachmentOperations.length === 0 }), _jsx(Modal, { close: isAttachNotDone ? handleClose : handleExit, footer: modalFooter(), isOpen: isModalOpen, title: _jsxs(Box, { display: "flex", gap: 8, children: [_jsx(LargerText, { children: _jsx(Icon, { name: "Link" }) }), _jsx(LargerText, { children: "Attachment" })] }), children: _jsx(AttachmentList, {}) })] }));
}
