import { Alert, GlyphButton } from '@theorchard/suite-components';
import React from 'react';
import { PopupModal } from 'src/components/shared/popup-modal';
import { useHistory, useParams } from 'react-router-dom';
import { useDeleteCustomPayment } from 'src/apollo/mutations/custom-payment/delete-custom-payment';
import { getPaymentsListPage } from 'src/urls/frontend-royalties';

const CLASS_NAME = 'CustomPaymentDelete';
const CONTAINER_CLASS_NAME = `${CLASS_NAME}-Container`;

const CustomPaymentDelete = () => {
    const { customPaymentId } = useParams<{
        customPaymentId: string;
    }>();
    const history = useHistory();
    const [isPopupOpen, setIsPopupOpen] = React.useState(false);
    const { deleteCustomPayment, loading, error } = useDeleteCustomPayment();

    const onSubmit = () =>
        deleteCustomPayment({
            variables: { worksheetPaymentCustomId: customPaymentId },
        })
            .then(() => history.push(getPaymentsListPage))
            .catch(() => {});

    return (
        <div className={CONTAINER_CLASS_NAME}>
            <GlyphButton
                className="delete-button"
                onClick={() => setIsPopupOpen(true)}
                name="trash"
            />
            <PopupModal
                className={CLASS_NAME}
                closeHandler={() => setIsPopupOpen(false)}
                closeButtonText="Cancel"
                saveHandler={onSubmit}
                saveButtonText="Delete Payment"
                saveButtonVariant="danger"
                modalContent={
                    <section>
                        {error && (
                            <Alert variant="error" text={error.message} />
                        )}
                        Deleting this payment will be permanent.
                    </section>
                }
                isOpen={isPopupOpen}
                isSaveButtonDisabled={loading}
                headerLabel="Delete This Payment?"
            />
        </div>
    );
};

export default CustomPaymentDelete;
