import { uniqBy } from 'lodash-es';
import React, { useEffect, useState } from 'react';
import {
    ErrorMessage,
    InfoMessage,
    LoadingPageIndicator,
    Modal,
    Section,
    Status,
    Stepper,
    PageHeader,
    type Step,
    Tag,
    LoadingSpinner,
    HelpTooltip,
    MetadataList,
    Button,
    useToast,
} from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import { useFeatureFlag } from '@theorchard/suite-frontend';
import { useParams } from 'react-router-dom';
import { DpPaymentAction } from 'src/apollo/definitions/globalTypes';
import { useReplaceDpPayments } from 'src/apollo/mutations/replace-dp-payments';
import { useUpdateDpPayments } from 'src/apollo/mutations/update-dp-payments';
import { useGetAdjustmentsFileData } from 'src/apollo/queries/collaborators';
import { useCollaboratorsDpPaymentsQuery } from 'src/apollo/queries/collaborators/dp-payments';
import { useCollaboratorsPeriodDetailQuery } from 'src/apollo/queries/collaborators/period-detail';
import { useCollaboratorsBreadcrumbs } from 'src/hooks/breadcrumbs/collaborators';
import {
    getDateFromDateTimeStamp,
    getLongDateFromDateTimeStamp,
} from 'src/utils/date-helpers';
import { formatNumberWithCommas } from 'src/utils/number-helper';
import AdjustmentUploadArea from './adjustment-upload-area';
import CollaboratorsStartCalculationButton from './collaborators-start-calculation-button';
import { useCreateDpPaymentTransactions } from 'src/apollo/mutations/collaborators';
import { useSubmitDpPayments } from 'src/apollo/mutations/submit-dp-payments';
import { USER_FEATURES } from 'src/constants';
import './collaborators-period-detail.scss';

const EMPTY_FIELD = '--';
const POLLING_INTERVAL = 2000;

const formatDecimal = (n: number) => formatNumberWithCommas(n.toFixed(2), true);
const valOrEmpty = (cond: boolean = false, val?: string | number) =>
    cond ? val! : EMPTY_FIELD;
const decOrEmpty = (cond: boolean = false, n?: number) =>
    cond ? formatDecimal(n!) : EMPTY_FIELD;

const Panel: React.FC<
    React.PropsWithChildren<{
        title: string;
    }>
> = ({ title, children }) => {
    return (
        <Section className="Panel">
            <Section.Body>
                <Section>
                    <Section.Header title={title} />
                    <Section.Body>{children}</Section.Body>
                </Section>
            </Section.Body>
        </Section>
    );
};

export const CLASS_NAME = 'CollaboratorsPeriodDetail';
export const CollaboratorsPeriodDetail: React.FC<{
    statementPeriodId?: string;
}> = () => {
    const { statementPeriodId: abacusStatementPeriodId } = useParams<{
        statementPeriodId: string;
    }>();
    const [generateAdjustmentsFileLoading, setGenerateAdjustmentsFileLoading] =
        useState(false);
    const [generatePaymentApprovalLoading, setGeneratePaymentApprovalLoading] =
        useState(false);
    const [generatePaymentUploadLoading, setGeneratePaymentUploadLoading] =
        useState(false);
    const [isSendPaymentsModalOpen, setIsSendPaymentsModalOpen] =
        useState(false);
    const isPayoneerApiIntegrationEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_COLLABORATORS_PAYONEER_API_INTEGRATION
    );

    const {
        data: statementPeriodData,
        loading: statementPeriodLoading,
        error: statementPeriodError,
        refetch: refetchStatementPeriod,
        startPolling,
        stopPolling,
    } = useCollaboratorsPeriodDetailQuery(abacusStatementPeriodId);

    const getAdjustmentsFileData = useGetAdjustmentsFileData(
        abacusStatementPeriodId
    );

    const { data: dpPaymentsData } = useCollaboratorsDpPaymentsQuery({
        abacusStatementPeriodId,
    });

    const [replaceDpPayments, { loading: replaceDpPaymentsLoading }] =
        useReplaceDpPayments(abacusStatementPeriodId);

    const [approveDpPayments, { loading: approveDpPaymentsLoading }] =
        useUpdateDpPayments({
            abacusStatementPeriodId,
            action: DpPaymentAction.APPROVE,
        });

    const [
        createDpPaymentTransactions,
        { loading: createDpPaymentTransactionsLoading },
    ] = useCreateDpPaymentTransactions({
        abacusStatementPeriodId,
    });

    const [submitDpPayments, { loading: submitDpPaymentsLoading }] =
        useSubmitDpPayments(abacusStatementPeriodId);

    const toast = useToast();

    const selectedStatementPeriod = statementPeriodData?.abacusStatementPeriod;
    const isCurrentPeriod =
        selectedStatementPeriod?.statementPeriodStatus === 'current';
    const reportRunStarted =
        selectedStatementPeriod?.collaboratorsReportRun?.requestedDateTime;

    const revenueAllocations =
        selectedStatementPeriod?.collaboratorsReportRun
            ?.transactionAggregations;
    const hasRevenueAllocations =
        revenueAllocations && revenueAllocations.totalCount > 0;

    const whtAllocations =
        selectedStatementPeriod?.collaboratorsWhtAllocationTransactions;
    const hasWhtTransactions = (whtAllocations?.totalCount ?? 0) > 0;

    const whtAdjustments = selectedStatementPeriod?.collaboratorsWhtAdjustments;
    const hasWhtAdjustments = (whtAdjustments?.totalCount ?? 0) > 0;

    const dpPayments = dpPaymentsData?.dpPayments;
    const hasDpPayments = dpPayments && dpPayments.totalCount > 0;

    const dpTransactions =
        statementPeriodData?.abacusStatementPeriod
            ?.collaboratorsDirectPaymentTransactions;
    const hasDpTransactions = (dpTransactions?.totalCount ?? 0) > 0;

    // When the auto calc is triggered, we begin polling for transactions
    // added to the collaborator ledger. Once we have them, we stop polling.
    useEffect(() => {
        if (!reportRunStarted) return;
        const hasRevenueAllocations =
            (selectedStatementPeriod.collaboratorsReportRun
                ?.transactionAggregations.totalCount ?? 0) > 0;
        const hasPaymentTransactionFees =
            selectedStatementPeriod.collaboratorsPaymentFeeTransactions
                .totalCount > 0;
        if (hasRevenueAllocations && hasPaymentTransactionFees) {
            stopPolling();
        } else {
            startPolling(POLLING_INTERVAL);
        }
    }, [selectedStatementPeriod, reportRunStarted, startPolling, stopPolling]);

    const breadcrumbs = useCollaboratorsBreadcrumbs(
        selectedStatementPeriod?.statementPeriodId
    );

    if (statementPeriodLoading) {
        return <LoadingPageIndicator />;
    } else if (
        statementPeriodError ||
        !statementPeriodData ||
        !selectedStatementPeriod
    ) {
        return <ErrorMessage error={statementPeriodError} />;
    }

    const numberOfActiveClients = EMPTY_FIELD; // TODO: Replace with actual data (AS-3774)

    const periodStatus = ((): {
        text: string;
        variant: React.ComponentProps<typeof Status>['variant'];
    } => {
        if (hasDpTransactions) return { text: 'Completed', variant: 'success' };
        if (reportRunStarted)
            return { text: 'In Progress', variant: 'warning' };
        return { text: 'Not Started', variant: 'neutral' };
    })();

    const generateAdjustmentsFile = async () => {
        setGenerateAdjustmentsFileLoading(true);
        try {
            const [data, { writeAdjustmentsFile }] = await Promise.all([
                getAdjustmentsFileData(),
                import('./write-adjustments-file'),
            ]);
            await writeAdjustmentsFile(data, selectedStatementPeriod);
        } finally {
            setGenerateAdjustmentsFileLoading(false);
        }
    };

    const generatePaymentApprovalFiles = async () => {
        setGeneratePaymentApprovalLoading(true);
        try {
            const { writePaymentApprovalFiles } =
                await import('./write-payment-approval-files');
            await writePaymentApprovalFiles(
                dpPaymentsData,
                selectedStatementPeriod
            );
        } finally {
            setGeneratePaymentApprovalLoading(false);
        }
    };

    const generatePaymentUploadFiles = async () => {
        setGeneratePaymentUploadLoading(true);
        try {
            const { writePaymentUploadFiles } =
                await import('./write-payment-upload-files');
            await writePaymentUploadFiles(
                dpPaymentsData,
                selectedStatementPeriod
            );
        } finally {
            setGeneratePaymentUploadLoading(false);
        }
    };

    const handleSubmitDpPayments = async () => {
        try {
            await submitDpPayments();

            setIsSendPaymentsModalOpen(false);
            toast('Payments were successfully sent to Payoneer.');
        } catch {
            toast('Something went wrong.', { variant: 'error' });
        }
    };

    type StepStatus = 'inProgress' | 'needsAction' | 'complete';
    const getStepIcon = (
        number: number,
        status: StepStatus
    ): Pick<Step, 'icon'> => {
        switch (status) {
            case 'needsAction':
                return { icon: { variant: 'warning', glyphIcon: 'warning' } };
            case 'complete':
                return { icon: { variant: 'success', glyphIcon: 'check' } };
            default:
                return { icon: { variant: 'neutral', number } };
        }
    };

    type SubPanelStep = Step & { table?: React.ReactNode };
    const renderSubPanel = (params: {
        steps: SubPanelStep[];
        title?: string;
        loading?: boolean;
    }) => {
        const steps: Step[] = params.steps.map(step => ({
            className: 'SubPanel-step',
            ...step,
            description: step.table,
            body: (
                <>
                    {step.description && (
                        <p className="SubPanel-description">
                            {step.description}
                        </p>
                    )}
                    {step.body}
                </>
            ),
        }));

        return (
            <Section className="SubPanel">
                {params.title && <Section.Header title={params.title} />}
                <Section.Body>
                    {params.loading ? (
                        <div className="SubPanel-spinner">
                            <LoadingSpinner size={48} show />
                            <p>
                                The calculation can take several minutes. You
                                may leave this page while you wait for it to
                                complete.
                            </p>
                        </div>
                    ) : (
                        <Stepper layout="vertical" steps={steps} />
                    )}
                </Section.Body>
            </Section>
        );
    };

    const renderTable = (params: {
        countColumnName: string;
        countColumnTooltip?: string;
        countColumnValue: string | number;
        amountColumnValue: string | number;
    }) => {
        return (
            <div className="SubPanel-table">
                <table>
                    <thead>
                        <th>{params.countColumnName}</th>
                        <th>Amount</th>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <span className="amount-count">
                                    {params.countColumnValue}
                                    {params.countColumnTooltip && (
                                        <HelpTooltip
                                            message={params.countColumnTooltip}
                                            id={`${params.countColumnName}-tooltip`}
                                        />
                                    )}
                                </span>
                            </td>

                            <td>{params.amountColumnValue}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        );
    };

    const renderCollaboratorLedgerRevenueSubPanel = () => {
        const title = 'Revenue Allocations Added to Collaborator Ledgers';
        const status: StepStatus = hasRevenueAllocations
            ? 'complete'
            : 'inProgress';
        const isPolling = reportRunStarted && !hasRevenueAllocations;

        return renderSubPanel({
            loading: isPolling,
            title: isPolling ? title : undefined,
            steps: [
                {
                    ...getStepIcon(1, status),
                    title,
                    description:
                        revenueAllocations?.completedDate &&
                        `Completed on ${getLongDateFromDateTimeStamp(revenueAllocations?.completedDate)}`,
                    table: renderTable({
                        countColumnName: 'Allocations',
                        countColumnValue: valOrEmpty(
                            hasRevenueAllocations,
                            revenueAllocations?.nonZeroCount
                        ),
                        countColumnTooltip: hasRevenueAllocations
                            ? `Allocations incl. zero-report: ${revenueAllocations.totalCount}`
                            : undefined,
                        amountColumnValue: decOrEmpty(
                            hasRevenueAllocations,
                            revenueAllocations?.currencyAgnosticTotal
                        ),
                    }),
                },
            ],
        });
    };

    const renderCollaboratorLedgerPaymentFeesSubPanel = () => {
        const title = 'Transaction Fees Applied to Collaborator Ledgers';
        const fees =
            selectedStatementPeriod.collaboratorsPaymentFeeTransactions;
        const hasPaymentTransactionFees = fees.totalCount > 0;
        const completedDate = fees.transactions[0]?.createdDate;
        const status: StepStatus = hasPaymentTransactionFees
            ? 'complete'
            : 'inProgress';
        const isPolling = reportRunStarted && !hasPaymentTransactionFees;

        return renderSubPanel({
            loading: isPolling,
            title: isPolling ? title : undefined,
            steps: [
                {
                    ...getStepIcon(1, status),
                    title,
                    description: !hasPaymentTransactionFees
                        ? undefined
                        : `Applied on ${getLongDateFromDateTimeStamp(completedDate)}`,
                    table: renderTable({
                        countColumnName: 'Transaction Fees',
                        countColumnValue: valOrEmpty(
                            hasPaymentTransactionFees,
                            fees.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasPaymentTransactionFees,
                            fees.nominalTotalAmount
                        ),
                    }),
                },
            ],
        });
    };

    const renderClientLedgerRevenueSubPanel = () => {
        const aggregations =
            selectedStatementPeriod.collaboratorsReportRun
                ?.contractSubtotalAggregations;
        const hasAggregations = (aggregations?.totalCount ?? 0) > 0;
        const adjustmentFileDownloadStatus: StepStatus = hasAggregations
            ? 'complete'
            : 'inProgress';

        const clientLedgerAllocations =
            selectedStatementPeriod.collaboratorsRevenueAdjustments;
        const hasClientLedgerAllocations =
            (clientLedgerAllocations?.totalCount ?? 0) > 0;
        const clientLedgerStatus: StepStatus = hasClientLedgerAllocations
            ? 'complete'
            : 'inProgress';

        return renderSubPanel({
            title: 'Revenue Allocations Added to Client Ledgers',
            steps: [
                {
                    ...getStepIcon(1, adjustmentFileDownloadStatus),
                    title: 'Revenue Allocation Adjustment File',
                    table: renderTable({
                        countColumnName: 'Allocations',
                        countColumnValue: valOrEmpty(
                            hasAggregations,
                            aggregations?.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasAggregations,
                            aggregations?.currencyAgnosticTotalAmount
                        ),
                    }),
                    ...(hasAggregations && {
                        titleAction: {
                            label: 'Download Adjustment File',
                            size: 'sm',
                            variant: 'secondary',
                            loading: generateAdjustmentsFileLoading,
                            onClick: generateAdjustmentsFile,
                        },
                    }),
                },
                {
                    ...getStepIcon(2, clientLedgerStatus),
                    title: 'Revenue Allocations on Client Ledger',
                    table: renderTable({
                        countColumnName: 'Allocations',
                        countColumnValue: valOrEmpty(
                            hasClientLedgerAllocations,
                            clientLedgerAllocations?.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasClientLedgerAllocations,
                            clientLedgerAllocations?.currencyAgnosticTotalAmount
                        ),
                    }),
                },
            ],
        });
    };

    const renderWhtAllocationSubPanel = () => {
        const whtTransactionsStatus: StepStatus = hasWhtTransactions
            ? 'complete'
            : 'inProgress';

        const whtAdjustmentsStatus: StepStatus = hasWhtAdjustments
            ? 'complete'
            : 'inProgress';

        return renderSubPanel({
            steps: [
                {
                    ...getStepIcon(1, whtTransactionsStatus),
                    title: 'Upload and apply WHT Allocations to the Collaborator Ledger',
                    table: renderTable({
                        countColumnName: 'Allocations',
                        countColumnValue: valOrEmpty(
                            hasWhtTransactions,
                            whtAllocations?.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasWhtTransactions,
                            whtAllocations?.nominalTotalAmount
                        ),
                    }),
                    body: hasWhtTransactions ? undefined : (
                        <AdjustmentUploadArea
                            onSuccess={async () =>
                                await refetchStatementPeriod()
                            }
                        />
                    ),
                },
                {
                    ...getStepIcon(2, whtAdjustmentsStatus),
                    title: 'Collaborator WHT Allocations Adjustments have been applied to client ledger',
                    table: renderTable({
                        countColumnName: 'Allocations',
                        countColumnValue: valOrEmpty(
                            hasWhtAdjustments,
                            whtAdjustments?.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasWhtAdjustments,
                            whtAdjustments?.currencyAgnosticTotalAmount
                        ),
                    }),
                },
            ],
        });
    };

    const renderPaymentsSubPanel = () => {
        const hasApprovedDpPayments =
            hasDpPayments && !!dpPayments.payments[0].approvedDate;
        const dpPaymentsUpdatePending =
            replaceDpPaymentsLoading || approveDpPaymentsLoading;
        const paymentApprovals =
            selectedStatementPeriod.collaboratorsPaymentApprovals;
        const hasApprovals = (paymentApprovals.totalCount ?? 0) > 0;
        const hasSentPayments =
            !!dpPayments?.payments[0]?.payoneerPaymentStatus;

        return renderSubPanel({
            steps: [
                {
                    ...getStepIcon(1, 'inProgress'),
                    title: 'Payment Approval Files',
                    table: renderTable({
                        countColumnName: 'Total Payments',
                        countColumnValue: valOrEmpty(
                            hasDpPayments,
                            dpPayments?.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasDpPayments,
                            dpPayments?.currencyAgnosticTotalAmount
                        ),
                    }),
                    titleAction: !hasDpPayments
                        ? {
                              label: 'Generate',
                              disabled:
                                  !hasWhtTransactions ||
                                  dpPaymentsUpdatePending,
                              loading: replaceDpPaymentsLoading,
                              size: 'sm',
                              variant: 'secondary',
                              onClick: () => replaceDpPayments(),
                          }
                        : undefined,
                    ...(hasDpPayments
                        ? {
                              ...getStepIcon(1, 'complete'),
                              description: `Completed on ${getLongDateFromDateTimeStamp(dpPayments.payments[0].createdDate)}`,
                              body: (
                                  <div
                                      className={`${CLASS_NAME}-approval-actions`}
                                  >
                                      <Button
                                          disabled={dpPaymentsUpdatePending}
                                          loading={
                                              generatePaymentApprovalLoading
                                          }
                                          onClick={() =>
                                              generatePaymentApprovalFiles()
                                          }
                                      >
                                          <GlyphIcon
                                              name="download"
                                              size={16}
                                          />
                                          Download
                                      </Button>
                                      <Button
                                          variant="tertiary"
                                          onClick={() => replaceDpPayments()}
                                          loading={replaceDpPaymentsLoading}
                                          disabled={
                                              hasApprovedDpPayments ||
                                              dpPaymentsUpdatePending
                                          }
                                      >
                                          <GlyphIcon name="refresh" size={16} />
                                          Re-Generate
                                      </Button>
                                  </div>
                              ),
                          }
                        : {}),
                },
                {
                    ...getStepIcon(
                        2,
                        hasApprovedDpPayments ? 'complete' : 'inProgress'
                    ),
                    title: 'Confirm Approval Files',
                    titleAction: !hasApprovedDpPayments
                        ? {
                              label: 'Confirm',
                              disabled:
                                  dpPaymentsUpdatePending || !hasDpPayments,
                              loading: approveDpPaymentsLoading,
                              size: 'sm',
                              variant: 'secondary',
                              onClick: () => void approveDpPayments(),
                          }
                        : undefined,
                    description: hasApprovedDpPayments
                        ? `Confirmed on ${getLongDateFromDateTimeStamp(dpPayments.payments[0].approvedDate!)}`
                        : undefined,
                },
                ...(!isPayoneerApiIntegrationEnabled
                    ? [
                          {
                              ...getStepIcon(
                                  3,
                                  hasApprovedDpPayments && hasApprovals
                                      ? 'complete'
                                      : 'inProgress'
                              ),
                              title: 'Generate Payoneer Upload Files',
                              table: renderTable({
                                  countColumnName: 'Total Payments',
                                  countColumnValue: valOrEmpty(
                                      hasApprovedDpPayments && hasApprovals,
                                      paymentApprovals?.totalCount
                                  ),
                                  amountColumnValue: decOrEmpty(
                                      hasApprovedDpPayments && hasApprovals,
                                      paymentApprovals.nominalTotalAmount
                                  ),
                              }),
                              ...(hasApprovals
                                  ? {
                                        body: (
                                            <div
                                                className={`${CLASS_NAME}-approval-actions`}
                                            >
                                                <Button
                                                    loading={
                                                        generatePaymentUploadLoading
                                                    }
                                                    disabled={
                                                        !hasApprovedDpPayments
                                                    }
                                                    onClick={() =>
                                                        void generatePaymentUploadFiles()
                                                    }
                                                >
                                                    <GlyphIcon
                                                        name="download"
                                                        size={16}
                                                    />
                                                    Download
                                                </Button>
                                            </div>
                                        ),
                                    }
                                  : {}),
                          } as SubPanelStep,
                      ]
                    : []),
                ...(isPayoneerApiIntegrationEnabled
                    ? [
                          {
                              ...getStepIcon(
                                  3,
                                  hasSentPayments ? 'complete' : 'inProgress'
                              ),
                              title: 'Send Payments to Payoneer',
                              titleAction: hasSentPayments
                                  ? undefined
                                  : {
                                        label: 'Send',
                                        disabled: !hasApprovals,
                                        variant: 'primary',
                                        size: 'sm',
                                        onClick: () =>
                                            setIsSendPaymentsModalOpen(true),
                                    },
                          } as SubPanelStep,
                      ]
                    : []),
                {
                    ...getStepIcon(
                        4,
                        hasDpTransactions ? 'complete' : 'inProgress'
                    ),
                    title: isPayoneerApiIntegrationEnabled
                        ? 'Payments applied to Collaborator Ledger'
                        : 'Apply Payments to Collaborator Ledgers',
                    table: renderTable({
                        countColumnName: 'Total Payments',
                        countColumnValue: valOrEmpty(
                            hasDpTransactions,
                            dpTransactions?.totalCount
                        ),
                        amountColumnValue: decOrEmpty(
                            hasDpTransactions,
                            dpTransactions?.nominalTotalAmount
                        ),
                    }),
                    ...(!isPayoneerApiIntegrationEnabled
                        ? {
                              titleAction: {
                                  label: 'Apply',
                                  disabled: !hasApprovals || hasDpTransactions,
                                  onClick: async () =>
                                      await createDpPaymentTransactions(),
                                  loading: createDpPaymentTransactionsLoading,
                              },
                          }
                        : {}),
                },
            ],
        });
    };

    return (
        <div className={CLASS_NAME}>
            <PageHeader
                breadcrumbs={breadcrumbs}
                mainContent={{
                    title: selectedStatementPeriod.statementPeriodName,
                    append: () => (
                        <Status
                            className={`${CLASS_NAME}-status`}
                            filled
                            variant={periodStatus.variant}
                            text={periodStatus.text}
                        />
                    ),
                }}
                actions={() => (
                    <CollaboratorsStartCalculationButton
                        {...selectedStatementPeriod}
                        reportRunStarted={reportRunStarted}
                        isCurrentPeriod={isCurrentPeriod}
                        onSuccess={() => startPolling(POLLING_INTERVAL)}
                    />
                )}
                topMetadata={{
                    left: () => (
                        <>
                            <Tag variant="category" text="Calculation" />
                            <MetadataList
                                items={[
                                    {
                                        label: '#DP-Active Clients (Terms Accepted):',
                                        value: numberOfActiveClients,
                                        layout: 'horizontal',
                                    },
                                    {
                                        label: 'Calculation Started:',
                                        value: ` ${valOrEmpty(reportRunStarted, getDateFromDateTimeStamp(reportRunStarted))}`,
                                        layout: 'horizontal',
                                    },
                                ]}
                            />
                        </>
                    ),
                }}
            />
            <div>
                {!reportRunStarted ? (
                    <InfoMessage
                        className={`${CLASS_NAME}-empty-state`}
                        message="No calculation yet."
                        body="Please click on “start calculation” button above to initiate the process of the calculation."
                        size={'lg'}
                    />
                ) : (
                    <div>
                        <Panel title="Collaborator Direct Payments Revenue Allocation">
                            {renderCollaboratorLedgerRevenueSubPanel()}
                            {renderCollaboratorLedgerPaymentFeesSubPanel()}
                            {renderClientLedgerRevenueSubPanel()}
                        </Panel>
                        <Panel title="Collaborator Direct Payments WHT Allocation">
                            {renderWhtAllocationSubPanel()}
                        </Panel>
                        <Panel title="Approval & Funding Confirmation">
                            {renderPaymentsSubPanel()}
                        </Panel>
                    </div>
                )}
            </div>
            {isPayoneerApiIntegrationEnabled && (
                <Modal
                    isOpen={isSendPaymentsModalOpen}
                    onRequestClose={() => setIsSendPaymentsModalOpen(false)}
                    title="Are you sure you want to send payments to Payoneer?"
                    confirmButtonProps={{
                        title: 'Yes, Send Payments',
                        variant: 'primary',
                        loading: submitDpPaymentsLoading,
                        onClick: handleSubmitDpPayments,
                    }}
                >
                    <div data-testid="send-payments-modal-content">
                        {'This will send '}
                        <span className="suite-text-bold">
                            {
                                selectedStatementPeriod
                                    .collaboratorsPaymentApprovals.totalCount
                            }
                        </span>
                        {' payments valued at '}
                        <span className="suite-text-bold">
                            {formatDecimal(
                                selectedStatementPeriod
                                    .collaboratorsPaymentApprovals
                                    .nominalTotalAmount
                            )}
                        </span>
                        {' to Payoneer. Payments are across '}
                        <span className="suite-text-bold">
                            {
                                uniqBy(
                                    dpPayments?.payments,
                                    'payoneerProgramId'
                                ).length
                            }
                        </span>
                        {' Programs.'}
                        <div>
                            These payments will be added to collaborator ledgers
                            automatically.
                        </div>
                    </div>
                </Modal>
            )}
        </div>
    );
};

export default CollaboratorsPeriodDetail;
