import { Button, useToast } from '@theorchard/suite-components';
import React, { useCallback, useState } from 'react';
import { PopupModal } from '../shared/popup-modal';
import { useTriggerCollaboratorAutoReportRun } from 'src/apollo/mutations/collaborators';
import { CLASS_NAME } from './collaborators-period-detail';

type CollaboratorsStartCalculationButtonProps = {
    statementPeriodId: string;
    statementPeriodName: string;
    reportRunStarted?: boolean;
    isCurrentPeriod?: boolean;
    onSuccess?: () => void;
};

const getModalHeader = (periodName: string) =>
    `Are you sure you want to start the Collaborator calculation for ${periodName}?`;
const modalContent = (
    <p>
        Please ensure all client accounting calculations are complete, approved,
        and that the Database refresh is completed before confirming this step!
        This step will calculate collaborator allocations, update their
        royalties, and apply relevant transaction fees to each collaborator.
    </p>
);

const CollaboratorsStartCalculationButton: React.FC<
    CollaboratorsStartCalculationButtonProps
> = ({
    statementPeriodId,
    statementPeriodName,
    reportRunStarted,
    isCurrentPeriod,
    onSuccess,
}) => {
    const [showConfirmationModal, setShowConfirmationModal] = useState(false);
    const addToast = useToast();

    const [
        triggerCollaboratorsAutoReportRun,
        { data: calculationData, loading: calculationLoading },
    ] = useTriggerCollaboratorAutoReportRun();

    const triggerCalculations = useCallback(async () => {
        setShowConfirmationModal(false);

        const result = await triggerCollaboratorsAutoReportRun({
            variables: { statementPeriodId },
        });
        const triggerResponse = result?.data?.triggerCollaboratorsAutoReportRun;

        if (
            triggerResponse &&
            triggerResponse.__typename === 'CollaboratorReportRun'
        ) {
            addToast('Calculation started');
            onSuccess?.();
        } else {
            addToast(
                triggerResponse?.message ?? 'Failed to start calculation',
                { variant: 'error' }
            );
        }
    }, [triggerCollaboratorsAutoReportRun, statementPeriodId, addToast]);

    const calculationTriggered =
        calculationData?.triggerCollaboratorsAutoReportRun.__typename ===
        'CollaboratorReportRun';
    const disabled =
        !isCurrentPeriod || reportRunStarted || calculationTriggered;

    return (
        <>
            <Button
                variant="primary"
                data-testid="start-calculation-button"
                onClick={() => setShowConfirmationModal(true)}
                disabled={disabled}
                loading={calculationLoading}
            >
                Start Calculation
            </Button>
            {showConfirmationModal && (
                <PopupModal
                    isOpen={showConfirmationModal}
                    closeHandler={() => setShowConfirmationModal(false)}
                    saveHandler={triggerCalculations}
                    saveButtonText="Yes, Start Calculation"
                    headerLabel={getModalHeader(statementPeriodName)}
                    modalContent={modalContent}
                    className={`${CLASS_NAME}-modal`}
                />
            )}
        </>
    );
};

export default CollaboratorsStartCalculationButton;
