// 'use no memo' — opt out of React Compiler memoization. This file has
// a ~90-line useEffect doing guarded property access on the
// `adjustmentFile` state plus event handlers using non-null assertions
// `adjustmentFile!.X`. Production sourcemap traced a runtime crash
// (Cannot read properties of null (reading 'statementPeriodAdjustmentFileId'))
// to line 316 col 6 — the closing brace of that useEffect, indicating
// React Compiler had attributed many memoized cache slots to that one
// position. Until the `!.` assertions across this file are audited
// end-to-end (separate task), keep the compiler out.
'use no memo';

import React, { useEffect, useState } from 'react';
import { useApolloClient } from '@apollo/client';
import {
    Alert,
    Button,
    GlyphButton,
    LoadingPageIndicator,
    Modal,
    Status,
    Tag,
    UploadArea,
    useToast,
} from '@theorchard/suite-components';
import { PageHeader as SuitePageHeader } from '@theorchard/suite-components';
import { PageHeader } from '../shared/pageHeader';
import { GlyphIcon } from '@theorchard/suite-icons';
import isEmpty from 'lodash-es/isEmpty';
import { useParams, useHistory, useLocation } from 'react-router-dom';
import { AbacusDag, SortOrder } from 'src/apollo/definitions/globalTypes';
import { useCreateAbacusEvent } from 'src/apollo/mutations/abacus-event';
import { useUpdateAbacusState } from 'src/apollo/mutations/abacus-state';
import { useSoftDeleteStatementPeriodAdjustmentFile } from 'src/apollo/mutations/statement-period-adjustment-file';
import {
    useStatementPeriodAdjustmentFilesAndStatus,
    getStatementPeriodAdjustmentFileAndStatus,
    getStatementPeriodAdjustmentFilesList,
} from 'src/apollo/queries/adjustment';
import { ADJUSTMENT_FILE_STATUSES_MAP } from 'src/apollo/type-constants/adjustment';
import { ADJUSTMENT_ERROR_MESSAGE } from 'src/apollo/type-constants/adjustment';
import AdjustmentsBatchList from 'src/components/adjustments/adjustments-batch-list';
import { useAdjustmentBreadcrumbs } from 'src/hooks/breadcrumbs/adjustments';
import {
    DEFAULT_ITEMS_PER_PAGE,
    STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS,
    USER_FEATURES,
} from 'src/constants';
import type { GetStatementPeriodAdjustmentFileAndStatusQuery } from 'src/apollo/queries/adjustment/__generated__/get-statement-period-adjustment-file-and-status';
import type { GetStatementPeriodAdjustmentFileAndStatesQuery } from 'src/apollo/queries/adjustment/__generated__/statement-period-adjustment-file-and-states';

type AbacusStatementPeriodAdjustmentFile = NonNullable<
    GetStatementPeriodAdjustmentFileAndStatesQuery['abacusStatementPeriodAdjustmentFile']
>;
type ActionStateTypes =
    AbacusStatementPeriodAdjustmentFile['actionStates'] extends
        | (infer T)[]
        | null
        ? T
        : null;

type AbacusStatementPeriodAdjustmentFilesList = NonNullable<
    GetStatementPeriodAdjustmentFileAndStatusQuery['abacusStatementPeriodAdjustmentFilesList']
>;
type AbacusStatementPeriodAdjustmentFileItem =
    AbacusStatementPeriodAdjustmentFilesList['items'][0];
import { isFeatureFlagEnabled } from 'src/utils/feature-flag';
import { formatNumberWithCommas } from 'src/utils/number-helper';
import { ABACUS_ACTION_STATUSES } from '@theorchard/accounting-apps-shared';
import RunTimerWithStatus from '../shared/run-timer-with-status';
import { useDagRunTimesQuery } from 'src/apollo/queries/dag-run-times';

export const AdjustmentsBatch: React.FC = () => {
    const { batchId } = useParams<{
        batchId: string;
    }>();
    const client = useApolloClient();
    const history = useHistory();
    const location = useLocation<{ autoGenerated?: boolean }>();
    const toast = useToast();

    const [adjustmentFile, setAdjustmentFile] =
        useState<AbacusStatementPeriodAdjustmentFileItem | null>(null);
    const [isApproving, setIsApproving] = useState<boolean>(false);
    const [isApproved, setIsApproved] = useState<boolean>(false);
    const [isApplied, setIsApplied] = useState<boolean>(false);
    const [isApplying, setIsApplying] = useState<boolean>(false);
    const [isConfirmButtonDisabled, setIsConfirmButtonDisabled] =
        useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [applyError, setApplyError] = useState<boolean>(false);
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [isApplyModalOpen, setIsApplyModalOpen] = useState(false);
    const [applyStatus, setApplyStatus] = useState<
        ActionStateTypes | undefined | null
    >(undefined);
    const isFeatureApprovedManualAdjustmentsUsersEnabled = isFeatureFlagEnabled(
        USER_FEATURES.ABACUS_MANUAL_ADJUSTMENTS_APPROVED_USERS
    );
    const isAutoGenerateEnabled = isFeatureFlagEnabled(
        USER_FEATURES.ABACUS_AUTO_GENERATE_ADJUSTMENTS_FLOWTHROUGH
    );
    const isAutoGenerated =
        isAutoGenerateEnabled && location.state?.autoGenerated === true;
    const [isGenerationInProgress, setIsGenerationInProgress] =
        useState(isAutoGenerated);

    const { data: applyFileDagRunTimes } = useDagRunTimesQuery(
        AbacusDag.APPLY_PENDING_ADJUSTMENTS
    );
    const avgApplyTime =
        applyFileDagRunTimes?.abacusDagRunTimes.averageRunTimeSeconds || 0;
    const p95ApplyTime =
        applyFileDagRunTimes?.abacusDagRunTimes.maxRunTimeSeconds || 0;
    const { updateAbacusState } = useUpdateAbacusState([
        {
            query: getStatementPeriodAdjustmentFilesList,
            variables: {
                limit: DEFAULT_ITEMS_PER_PAGE,
                offset: 0,
                sortOrder: SortOrder.DESC,
            },
        },
        {
            query: getStatementPeriodAdjustmentFileAndStatus,
            variables: { statementPeriodAdjustmentFileId: batchId },
        },
    ]);
    const breadcrumbs = useAdjustmentBreadcrumbs();

    const {
        data,
        error: queryError,
        loading,
        startPolling,
        stopPolling,
    } = useStatementPeriodAdjustmentFilesAndStatus(batchId);

    const softDeleteStatementPeriodAdjustmentFile =
        useSoftDeleteStatementPeriodAdjustmentFile();
    const createAbacusEvent = useCreateAbacusEvent();

    const getActionState = (actionType: string) => {
        const { actionStates } = adjustmentFile!;
        const actionState = actionStates?.find(
            action => action!.actionName === actionType
        );
        return actionState;
    };

    const hasErrorStatus = () => {
        if (adjustmentFile && adjustmentFile.actionStates)
            return adjustmentFile?.actionStates.some(
                action => action.actionStatus === ABACUS_ACTION_STATUSES.ERROR
            );

        return false;
    };

    const deleteBatch = async () => {
        try {
            await softDeleteStatementPeriodAdjustmentFile({
                variables: {
                    statementPeriodAdjustmentFileId: batchId,
                },
            });
        } catch (e) {
            if (e instanceof Error) {
                setError(e.message);
            }
        }
    };

    const goToAdjustmentsAfterDelete = async () => {
        await deleteBatch();
        toast(`Batch ${batchId} has been successfully deleted.`);
        history.push('/adjustments');
    };

    useEffect(() => {
        if (!isEmpty(applyStatus)) {
            if (applyStatus!.actionStatus === ABACUS_ACTION_STATUSES.RUNNING) {
                setIsApplying(true);
                setIsApplyModalOpen(false);
            }
            if (
                applyStatus!.actionStatus === ABACUS_ACTION_STATUSES.INIT ||
                applyStatus!.actionStatus === ABACUS_ACTION_STATUSES.RUNNING
            ) {
                startPolling(2000);
            }
            if (applyStatus!.actionStatus === ABACUS_ACTION_STATUSES.ERROR) {
                stopPolling();
                setIsApplying(false);
                setIsApplyModalOpen(false);
                setApplyError(true);
            }
        }
    }, [applyStatus]);

    useEffect(() => {
        if (isAutoGenerated && isGenerationInProgress) {
            startPolling(2000);
        }
    }, []);

    useEffect(() => {
        if (data?.abacusStatementPeriodAdjustmentFilesList) {
            if (
                data?.abacusStatementPeriodAdjustmentFilesList?.totalCount > 0
            ) {
                setAdjustmentFile(
                    data.abacusStatementPeriodAdjustmentFilesList.items[0]
                );
            } else {
                setError('Batch not found');
            }
        }
    }, [
        data,
        loading,
        isApproved,
        isApplying,
        isGenerationInProgress,
        batchId,
    ]);

    useEffect(() => {
        if (queryError && !isGenerationInProgress) {
            setError(queryError.message);
        }
    }, [queryError]);

    useEffect(() => {
        if (adjustmentFile) {
            setIsApproved(
                getActionState(
                    STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.APPROVE_FILE
                )?.actionStatus === ABACUS_ACTION_STATUSES.COMPLETE
            );
            const isFileApplied =
                getActionState(
                    STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.APPLY_FILE
                )?.actionStatus === ABACUS_ACTION_STATUSES.COMPLETE;

            setIsApplied(isFileApplied);

            if (isFileApplied) {
                stopPolling();
                if (isApplying) {
                    toast(`Batch ${batchId} has been successfully applied.`);
                }
                setIsApplying(false);
                client.cache.evict({
                    id: 'ROOT_QUERY',
                    fieldName: 'abacusStatementPeriodAdjustmentFilesList',
                });
            } else {
                setApplyStatus(
                    getActionState(
                        STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.APPLY_FILE
                    )
                );
            }
            if (isAutoGenerateEnabled && adjustmentFile.batchType == 'auto') {
                const uploadStatus = getActionState(
                    STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.UPLOAD_FILE
                )?.actionStatus;
                const validateStatus = getActionState(
                    STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.VALIDATE_FILE
                )?.actionStatus;
                const importStatus = getActionState(
                    STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.IMPORT_FILE
                )?.actionStatus;

                const COMPLETE = ABACUS_ACTION_STATUSES.COMPLETE;
                const ERROR = ABACUS_ACTION_STATUSES.ERROR;
                const RUNNING = ABACUS_ACTION_STATUSES.RUNNING;

                const isGenerating =
                    [uploadStatus, validateStatus, importStatus].includes(
                        RUNNING
                    ) || adjustmentFile?.status === 'generating';

                if (isGenerating) {
                    setIsGenerationInProgress(isGenerating);
                    startPolling(2000);
                }

                const isGenerated =
                    (uploadStatus === COMPLETE &&
                        adjustmentFile?.status === 'no_records') ||
                    (uploadStatus === COMPLETE &&
                        validateStatus === COMPLETE &&
                        importStatus === COMPLETE);

                const isGenerateFailed = [
                    uploadStatus,
                    validateStatus,
                    importStatus,
                ].includes(ERROR);

                if (
                    uploadStatus === COMPLETE &&
                    validateStatus === COMPLETE &&
                    importStatus === COMPLETE &&
                    isGenerationInProgress
                )
                    toast(
                        'The flowthrough adjustment has successfully been created.'
                    );

                if (isGenerateFailed && isGenerationInProgress)
                    toast(
                        'The flowthrough adjustment has failed to generate.',
                        { variant: 'error' }
                    );

                if (isGenerated || isGenerateFailed) {
                    setIsGenerationInProgress(false);
                    stopPolling();
                }
            }
        }
    }, [adjustmentFile]);

    const approveBatch = (): void => {
        try {
            setIsApproving(true);
            const actionState = getActionState(
                STATEMENT_PERIOD_ADJUSTMENT_UPLOAD_ACTIONS.APPROVE_FILE
            );
            const updateStateVariables = {
                abacusStateId: actionState!.abacusStateId,
                actionStatus: ABACUS_ACTION_STATUSES.COMPLETE,
            };
            updateAbacusState({ variables: updateStateVariables });
            toast(
                <div>
                    Batch {adjustmentFile?.statementPeriodAdjustmentFileId} has
                    been successfully approved.
                </div>
            );
        } catch (e) {
            setIsApproving(false);
            if (e instanceof Error) {
                setError(e.message);
            }
        }
    };

    const applyBatch = async () => {
        if (!adjustmentFile) return;
        try {
            createAbacusEvent({
                variables: {
                    eventName: 'apply_pending_adjustments',
                    targetId: adjustmentFile.statementPeriodAdjustmentFileId,
                    targetType: 'statement_period_adjustment_file',
                },
            });
            setIsConfirmButtonDisabled(true);
        } catch (e) {
            if (e instanceof Error) {
                setError(e.message);
            }
        }
    };

    if (error) {
        return (
            <Alert
                variant="error"
                text={ADJUSTMENT_ERROR_MESSAGE}
                className="error-alert"
            />
        );
    }

    if (loading) return <LoadingPageIndicator />;

    const getAdjustmentStatus = () => {
        const isAutoGenerateFailed =
            isAutoGenerateEnabled &&
            adjustmentFile?.status === 'failed_to_generate';
        if (hasErrorStatus() && !isAutoGenerateFailed)
            return ADJUSTMENT_FILE_STATUSES_MAP.error;
        if (adjustmentFile && adjustmentFile?.status)
            return ADJUSTMENT_FILE_STATUSES_MAP[adjustmentFile?.status];
    };

    const getAdjustmentStatusVariant = () => {
        if (hasErrorStatus()) return ABACUS_ACTION_STATUSES.ERROR as 'error';
        const status = adjustmentFile?.status;
        if (status === 'applied') return 'success';
        if (status === 'approved') return 'success';
        if (status === 'error') return 'error';
        if (status === 'failed_to_generate') return 'error';

        return 'neutral';
    };

    const adjustmentStatus = getAdjustmentStatus() || '';
    const adjustmentStatusVariant = getAdjustmentStatusVariant();

    const isRetry = hasErrorStatus();
    const applyModalTitle = isRetry
        ? `Retry applying batch ${batchId}?`
        : `Are you sure you want to apply batch ${batchId}?`;

    const applyModalAlert = isRetry ? (
        <Alert
            variant="information"
            testId="applyModalRetryAlert"
            text={
                <span>
                    <b>Retrying previous apply attempt.</b>
                    <br />
                    The system will safely skip any adjustments that were
                    already applied. No duplicate entries will be created.
                </span>
            }
        />
    ) : (
        <Alert
            variant="warn"
            testId="applyModalAlert"
            text={
                <span>
                    <b>This action cannot be undone!</b>
                    <br />
                    All adjustments and expenses for the current statement
                    period will be applied to account ledgers, and you will not
                    be able to take any actions against them.
                </span>
            }
        />
    );

    return (
        <div className="AdjustmentsBatch" data-testid="adjustmentsBatchPage">
            <PageHeader breadcrumbs={breadcrumbs}>
                <div className="d-flex flex-column w-100">
                    <div className="AdjustmentsBatch-Header-Summary">
                        <div className="AdjustmentsBatch-Header-Top-Left-Summary-Content">
                            {isAutoGenerateEnabled &&
                                adjustmentFile?.batchType == 'auto' && (
                                    <Tag
                                        text="Auto-Generated Batch"
                                        data-testid="autoGeneratedBadge"
                                    />
                                )}
                            <label className="AdjustmentsBatch-Header-Label">
                                Total Adjustments &amp; Expenses:&nbsp;
                            </label>
                            <div data-testid="totalAdjustments">
                                {isAutoGenerateEnabled &&
                                adjustmentFile?.status &&
                                [
                                    'generating',
                                    'failed_to_generate',
                                    'no_records',
                                ].includes(adjustmentFile?.status)
                                    ? '-'
                                    : adjustmentFile?.validRowCount &&
                                      formatNumberWithCommas(
                                          adjustmentFile?.validRowCount,
                                          false
                                      )}
                            </div>
                        </div>
                        <div className="AdjustmentsBatch-Header-Top-Left-Summary-Content">
                            <label className="AdjustmentsBatch-Header-Label">
                                Total Amount (MUL):
                            </label>
                            <div data-testid="totalAmount">
                                {isAutoGenerateEnabled &&
                                adjustmentFile?.status &&
                                [
                                    'generating',
                                    'failed_to_generate',
                                    'no_records',
                                ].includes(adjustmentFile?.status)
                                    ? '-'
                                    : adjustmentFile?.totalRoundedAmountMulticurrency &&
                                      formatNumberWithCommas(
                                          adjustmentFile?.totalRoundedAmountMulticurrency,
                                          true
                                      )}
                            </div>
                        </div>
                    </div>

                    <div className="d-flex">
                        <SuitePageHeader.Title>{`Batch ${adjustmentFile?.statementPeriodAdjustmentFileId}`}</SuitePageHeader.Title>
                        {isAutoGenerateEnabled &&
                        adjustmentFile?.status === 'generating' ? (
                            <div
                                className="Status ml-2 mr-auto size-medium"
                                data-testid="Status"
                            >
                                <GlyphIcon name="inProgress" size={16} />
                                <div className="Status-body Status-inline">
                                    <span className="Status-text">
                                        {adjustmentStatus?.toString()}
                                    </span>
                                </div>
                            </div>
                        ) : (
                            <Status
                                filled
                                variant={adjustmentStatusVariant}
                                text={adjustmentStatus?.toString()}
                                className="ml-2 mr-auto"
                            />
                        )}

                        <GlyphButton
                            className="mr-2"
                            hidden={
                                isApplied ||
                                isApplying ||
                                (isAutoGenerateEnabled &&
                                    (loading ||
                                        isGenerationInProgress ||
                                        adjustmentFile?.status ===
                                            'generating'))
                            }
                            onClick={() => setIsDeleteModalOpen(true)}
                            name="trash"
                        />
                        <Button
                            className="mr-2"
                            disabled={
                                isApproved ||
                                isApproving ||
                                hasErrorStatus() ||
                                (isAutoGenerateEnabled &&
                                    (isGenerationInProgress ||
                                        !adjustmentFile?.validRowCount))
                            }
                            onClick={() => {
                                approveBatch();
                            }}
                        >
                            {isApproved ? (
                                <>
                                    <GlyphIcon name="check" size={16} />
                                    &nbsp;Approved
                                </>
                            ) : (
                                <>&nbsp;Approve</>
                            )}
                        </Button>
                        <Button
                            variant="primary"
                            disabled={
                                !isApproved ||
                                isApplied ||
                                isApplying ||
                                !isFeatureApprovedManualAdjustmentsUsersEnabled ||
                                (isAutoGenerateEnabled &&
                                    (isGenerationInProgress ||
                                        !adjustmentFile?.validRowCount))
                            }
                            onClick={() => setIsApplyModalOpen(true)}
                        >
                            {isApplied ? (
                                <>
                                    <GlyphIcon name="check" size={16} />
                                    &nbsp;Applied
                                </>
                            ) : isApplying ? (
                                <RunTimerWithStatus
                                    displayText="Applying"
                                    avgRunTime={avgApplyTime}
                                    p95RunningTime={p95ApplyTime}
                                    tooltipLocation="bottom"
                                />
                            ) : (
                                <>&nbsp;Apply</>
                            )}
                        </Button>
                        <Modal
                            isOpen={isDeleteModalOpen}
                            className="AdjustmentsBatch-Modal"
                            testId="softDeleteModal"
                            title={
                                <span
                                    className="AdjustmentsBatch-Modal-Title"
                                    data-testid="modalTitle"
                                >
                                    Are you sure you want to delete batch&nbsp;
                                    <span className="AdjustmentsBatch-Modal-Title-Batch">
                                        {batchId}
                                    </span>
                                    ?
                                </span>
                            }
                            onRequestClose={() => {
                                setIsDeleteModalOpen(false);
                            }}
                            onConfirm={async () => {
                                await goToAdjustmentsAfterDelete();
                            }}
                            cancelTitle="No, Cancel"
                            confirmTitle="Yes, Delete"
                        >
                            <span data-testid="modalDescription">
                                This action cannot be undone.
                            </span>
                        </Modal>
                        <Modal.Custom
                            className="AdjustmentsBatch-Modal"
                            isOpen={isApplyModalOpen}
                            onRequestClose={() => {
                                isConfirmButtonDisabled
                                    ? false
                                    : setIsApplyModalOpen(false);
                            }}
                            testId="applyModal"
                            title={
                                <span
                                    className="AdjustmentsBatch-Modal-Title"
                                    data-testid="applyModalTitle"
                                >
                                    {applyModalTitle}
                                </span>
                            }
                            customFooter={
                                <div className="ReactModal-footer AdjustmentsBatch-modal-buttons">
                                    <Button
                                        onClick={() => {
                                            setIsApplyModalOpen(false);
                                        }}
                                        variant="secondary"
                                        disabled={isConfirmButtonDisabled}
                                    >
                                        No, Cancel
                                    </Button>
                                    <Button
                                        onClick={() => {
                                            applyBatch();
                                        }}
                                        variant="primary"
                                        disabled={isConfirmButtonDisabled}
                                    >
                                        {isConfirmButtonDisabled && (
                                            <>
                                                <GlyphIcon
                                                    name="inProgress"
                                                    size={16}
                                                />
                                                &nbsp;
                                            </>
                                        )}
                                        Yes, Apply
                                    </Button>
                                </div>
                            }
                        >
                            {applyModalAlert}
                        </Modal.Custom>
                    </div>

                    <div className="AdjustmentsBatch-Header-Bottom">
                        <div className="AdjustmentsBatch-Header-Bottom-Left">
                            <label className="AdjustmentsBatch-Header-Label">
                                File Name:
                            </label>
                            <div>{adjustmentFile?.fileName}</div>
                        </div>
                        <div className="AdjustmentsBatch-Header-Bottom-Right">
                            <div className="AdjustmentsBatch-Header-Bottom-Right-Content">
                                <div data-testid="uploadedAt">
                                    <span className="AdjustmentsBatch-Header-Bottom-Right-Content-Label">
                                        Uploaded:&nbsp;
                                    </span>
                                    {adjustmentFile?.createdAt}
                                </div>
                                <div data-testid="uploadedBy">
                                    <span className="AdjustmentsBatch-Header-Bottom-Right-Content-Label">
                                        By:&nbsp;
                                    </span>
                                    {adjustmentFile?.createdByIdentity
                                        ? adjustmentFile?.createdByIdentity.name
                                        : adjustmentFile?.createdBy}
                                </div>
                            </div>
                            {adjustmentFile?.dateApproved && (
                                <div className="AdjustmentsBatch-Header-Bottom-Right-Content">
                                    <div className="AdjustmentsBatch-Header-Bottom-Right-Content-Divider"></div>
                                    <div data-testid="approvedAt">
                                        <span className="AdjustmentsBatch-Header-Bottom-Right-Content-Label">
                                            Approved:&nbsp;
                                        </span>
                                        {adjustmentFile?.dateApproved}
                                    </div>
                                    <div data-testid="approvedBy">
                                        <span className="AdjustmentsBatch-Header-Bottom-Right-Content-Label">
                                            By:&nbsp;
                                        </span>
                                        {adjustmentFile?.approvedByIdentity
                                            ? adjustmentFile?.approvedByIdentity
                                                  .name
                                            : adjustmentFile?.approvedBy}
                                    </div>
                                </div>
                            )}
                            {adjustmentFile?.dateApplied && (
                                <div className="AdjustmentsBatch-Header-Bottom-Right-Content">
                                    <div className="AdjustmentsBatch-Header-Bottom-Right-Content-Divider"></div>
                                    <div data-testid="appliedAt">
                                        <span className="AdjustmentsBatch-Header-Bottom-Right-Content-Label">
                                            Applied:&nbsp;
                                        </span>
                                        {adjustmentFile?.dateApplied}
                                    </div>
                                    <div data-testid="appliedBy">
                                        <span className="AdjustmentsBatch-Header-Bottom-Right-Content-Label">
                                            By:&nbsp;
                                        </span>
                                        {adjustmentFile?.appliedByIdentity
                                            ? adjustmentFile?.appliedByIdentity
                                                  .name
                                            : adjustmentFile?.appliedBy}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </PageHeader>
            <div>
                {applyError ? (
                    <Alert
                        variant="error"
                        text={
                            <span>
                                <b>
                                    Failed to apply adjustments for batch &quot;
                                    {batchId}&quot; due to an unexpected error.
                                </b>
                                <br />
                                Please try again or contact the tech team if
                                error persist.
                            </span>
                        }
                        className="AdjustmentsBatch-Apply-Error"
                    />
                ) : null}
            </div>
            {isAutoGenerateEnabled &&
            adjustmentFile?.batchType == 'auto' &&
            isGenerationInProgress ? (
                <div
                    className="AdjustmentsBatch-InProgress"
                    data-testid="adjustmentsInProgress"
                >
                    <UploadArea
                        disabled
                        inputId="batch-generation-loading"
                        info={{
                            illustration: 'spinner',
                            title: 'Adjustments in Progress',
                            description: 'Check back in a few minutes.',
                        }}
                        onUpload={() => {
                            return;
                        }}
                        testId="AdjustmentsGenerationLoadingArea"
                        variant="large"
                    />
                </div>
            ) : (
                <div data-testid="adjustmentsBatchList">
                    <AdjustmentsBatchList
                        batchType={adjustmentFile?.batchType}
                        batchStatus={adjustmentFile?.status}
                        isAutoGenerateEnabled={isAutoGenerateEnabled}
                    />
                </div>
            )}
        </div>
    );
};

export default AdjustmentsBatch;
