import React, { useEffect, useState } from 'react';
import { useApolloClient } from '@apollo/client';
import {
    Button,
    Col,
    Container,
    DatePicker,
    Form,
    Highlight,
    Label,
    Modal,
    Row,
    Switch,
    Tooltip,
} from '@theorchard/suite-components';
import { useFeatureFlag } from '@theorchard/suite-frontend';
import { GlyphIcon } from '@theorchard/suite-icons';
import cx from 'classnames';
import { isEmpty, isNumber, lowerCase } from 'lodash-es';
import { AbacusContractLifecycleStatus } from 'src/apollo/definitions/globalTypes';
import { useAbacusAccountFragment } from 'src/apollo/queries/account';
import { useReferenceSigningEntityFragment } from 'src/apollo/queries/reference-signing-entity';
import {
    CONTRACT_INTERVAL_TYPES,
    CONTRACT_LIFECYCLE_MODAL_SCREENS,
    TOOLTIP_EXECUTION_DATE,
    MAX_CONTRACT_LIFECYCLE_DETAIL_INTERVAL,
    PAID_BY_TOOLTIP_MSG,
    PAID_BY_SIGNING_ENTITY_TOOLTIP_MSG,
} from 'src/apollo/type-constants/contract';
import { CollectionPeriod } from 'src/components/contract-lifecycle-shared/collection-period';
import RunControllerSelect from 'src/components/contract-lifecycle-shared/run-controller-select';
import RunControllerDropdown from 'src/components/contract-lifecycle-shared/run-controller-dropdown';
import ContractTypeSelect from 'src/components/shared/contract-type-select';
import { ContractTypesDropdown } from 'src/components/shared/contract-types-dropdown';
import ReferenceSigningEntityDropdown from 'src/components/shared/reference-signing-entity-dropdown';
import ReferenceSigningEntitySelect from 'src/components/shared/reference-signing-entity-select';
import ReferenceSapProfitCenterDropdown from 'src/components/shared/reference-sap-profit-center-dropdown';
import {
    CONTRACT_TYPES,
    CONTRACT_TYPE_MAP,
    MAX_CHARACTERS,
    USER_FEATURES,
} from 'src/constants';
import useAccountSearch from 'src/hooks/account-search';
import { contractGeneralFormValidation } from 'src/utils/form-validations/contract-form-validation';
import { emptyStringsToNull } from 'src/utils/object-keys';
import { sanitizeTextInput } from 'src/utils/sanitize-text-input';
import type { GetAccountsListQuery } from 'src/apollo/queries/account/__generated__/get-accounts-list';
import type {
    Contract,
    ContractLifecycleSchedule,
} from 'src/types/abacus-contract-lifecycle';
import type { ListViewItem } from '@theorchard/suite-components';
import { YYYY_MM_DD } from '@theorchard/accounting-apps-shared';

type AbacusContract = NonNullable<
    NonNullable<GetAccountsListQuery['abacusAccounts']['items'][0]>['contracts']
>[0];

type AccountPaymentTerm = NonNullable<
    GetAccountsListQuery['abacusAccounts']['items'][0]['accountPaymentTerm']
>;
type AccountPaymentEntity = NonNullable<AccountPaymentTerm['paymentEntity']>;

export interface ContractLifecycleGeneralContractInformationScreenPropsTypes {
    /* eslint-disable no-unused-vars */
    setContract: (contract: Contract) => void;
    contract: Contract;
    contractLifecycleSchedules: ContractLifecycleSchedule[];
    existingPrimaryContract: AbacusContract | null;
    hasCollectionPeriod: boolean;
    isVisible: boolean;
    setContractLifecycleSchedules: (
        schedules: ContractLifecycleSchedule[]
    ) => void;
    setExistingPrimaryContract: (
        existingPrimaryContract: AbacusContract | null
    ) => void;
    setHasCollectionPeriod: (params: boolean) => void;
    setModalScreen: (screen: string) => void;
    setPaymentEntityName: (paymentEntityName: string | null) => void;
    setAccountName: (accountName: string | null) => void;
    /* eslint-enable no-unused-vars */
    saveHandler: () => void;
}
export const ContractLifecycleGeneralContractInformationScreen: React.FC<
    ContractLifecycleGeneralContractInformationScreenPropsTypes
> = ({
    contract,
    contractLifecycleSchedules,
    existingPrimaryContract,
    hasCollectionPeriod,
    isVisible,
    setContract,
    setContractLifecycleSchedules,
    setExistingPrimaryContract,
    setHasCollectionPeriod,
    setModalScreen,
    setPaymentEntityName,
    setAccountName,
    saveHandler,
}) => {
    const defaultContractLifecycleSchedule: ContractLifecycleSchedule = {
        renewalType: null,
        renewalOffsetDetailInterval: null,
        renewalOffsetDetailType: null,
        scheduleEnd: null,
        terminationNoticeDetailInterval: null,
        terminationNoticeDetailType: CONTRACT_INTERVAL_TYPES.DAYS.value,
        collectionPeriodDetailInterval: null,
        collectionPeriodDetailType: CONTRACT_INTERVAL_TYPES.DAYS.value,
    };
    const [contractLifecycleSchedule, setContractLifecycleSchedule] =
        useState<ContractLifecycleSchedule>(defaultContractLifecycleSchedule);
    const [errors, setErrors] = useState<
        Partial<Contract> & Partial<ContractLifecycleSchedule>
    >();
    const [referencePaymentEntity, setReferencePaymentEntity] =
        useState<AccountPaymentEntity | null>(null);
    const [
        shouldRenderGeneralNotesSection,
        setShouldRenderGeneralNotesSection,
    ] = useState<boolean>(!!contract.generalNote);
    const [shouldUpdatePaymentEntity, setShouldUpdatePaymentEntity] =
        useState<boolean>(false);
    const [isSavingContract, setIsSavingContract] = useState(false);
    const [skipRenewalRules, setSkipRenewalRules] = useState(false);
    const [shouldMarkAsPrimaryContract, setShouldMarkAsPrimaryContract] =
        useState<boolean>(false);
    const [
        shouldMarkAsPrimaryContractWithLifecycle,
        setShouldMarkAsPrimaryContractWithLifecycle,
    ] = useState<boolean>(false);
    const [
        isPrimaryContractUpdateConfirmModalOpen,
        setIsPrimaryContractUpdateConfirmModalOpen,
    ] = useState<boolean>(false);
    const [sapProfitCenters, setSapProfitCenters] = useState<
        Record<string, any>
    >({});

    // ACC-9395: TODO remove FF abacus_primary_contract
    const isFeaturePrimaryContractEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_PRIMARY_CONTRACT
    );

    const isFeatureSingleSupplyChainCompanyCodesEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_SINGLE_SUPPLY_CHAIN_COMPANY_CODES
    );

    const client = useApolloClient();

    const { accountId, renderAccountSearch } = useAccountSearch({
        className: errors?.accountId ? 'error accountSearch' : 'accountSearch',
        clearable: true,
        accountSearchResults: [],
        selectedOption: '',
        testId: 'accountSearchDropdown',
    });

    const account = useAbacusAccountFragment(accountId, client.cache);

    const signingEntity = useReferenceSigningEntityFragment(
        contract?.referenceSigningEntityId,
        client.cache
    );

    const handleContractTypeChange = (e: any) => {
        const value = e?.value || '';
        if (value === lowerCase(CONTRACT_TYPE_MAP.distribution)) {
            setHasCollectionPeriod(false);
        }
        setContract({
            ...contract,
            contractType: value,
            isPrimaryContract: false,
            runControllerId: null,
        });
        setExistingPrimaryContract(null);
    };

    const handleCollectionPeriodChange = (
        formField: string,
        inputValue: number | string | null | undefined
    ) => {
        if (
            formField === 'collectionPeriodDetailInterval' &&
            isNumber(inputValue) &&
            inputValue > MAX_CONTRACT_LIFECYCLE_DETAIL_INTERVAL
        )
            return;

        setContractLifecycleSchedule({
            ...contractLifecycleSchedule,
            [formField]: inputValue,
        });
    };

    const handleGeneralNotesChange = (
        e: React.ChangeEvent<HTMLInputElement>
    ) => {
        let value: string | null = e.target.value;

        if (value === '') {
            value = null;
        }
        setContract({
            ...contract,
            generalNote: value,
        });
    };

    const isNextButtonDisabled = (): boolean => {
        const optionalFields: (keyof Contract)[] = [
            'referencePaymentEntityId',
            'generalNote',
            'executionDate',
            'isPrimaryContract',
        ];
        let contractCopy = contract;
        if (!isFeatureSingleSupplyChainCompanyCodesEnabled) {
            const { referenceSapProfitCenterId, ...rest } = contract;
            contractCopy = rest;
        }
        const contractWithStringProcessed = emptyStringsToNull(contractCopy);

        const hasInvalidField = Object.entries(
            contractWithStringProcessed
        ).some(
            ([key, value]) =>
                !optionalFields.includes(key as keyof Contract) && !value
        );

        if (hasInvalidField) {
            return true;
        }

        if (
            hasCollectionPeriod &&
            !contractLifecycleSchedule.collectionPeriodDetailInterval
        ) {
            return true;
        }

        return false;
    };

    useEffect(() => {
        if (
            contractLifecycleSchedules.length > 0 &&
            contractLifecycleSchedules[0].renewalType
        ) {
            setContractLifecycleSchedule(contractLifecycleSchedules[0]);
        }
    }, [contractLifecycleSchedules]);

    useEffect(() => {
        if (!hasCollectionPeriod) {
            setContractLifecycleSchedule({
                ...contractLifecycleSchedule,
                collectionPeriodDetailInterval: null,
                collectionPeriodDetailType: CONTRACT_INTERVAL_TYPES.DAYS.value,
            });
        }
    }, [hasCollectionPeriod]);

    const syncFormState = () => {
        const { collectionPeriodDetailInterval } = contractLifecycleSchedule;
        const collectionPeriod =
            collectionPeriodDetailInterval &&
            parseInt(`${collectionPeriodDetailInterval}`);
        const formErrors = contractGeneralFormValidation(
            contract,
            collectionPeriod
        );

        if (Object.keys(formErrors).length > 0) {
            setErrors(formErrors);
            return;
        }

        if (contractLifecycleSchedules.length > 1)
            setContractLifecycleSchedules([
                contractLifecycleSchedule,
                contractLifecycleSchedules[1],
            ]);
        else setContractLifecycleSchedules([contractLifecycleSchedule]);

        if (shouldUpdatePaymentEntity) {
            setPaymentEntityName(
                referencePaymentEntity?.paymentEntityName || null
            );
            setAccountName(account?.accountName || null);
            setContract({
                ...contract,
                referencePaymentEntityId:
                    referencePaymentEntity?.referencePaymentEntityId || null,
            });
        }
    };
    const handleNextButtonClick = () => {
        syncFormState();
        setSkipRenewalRules(false);
        setIsSavingContract(false);
        if (shouldMarkAsPrimaryContractWithLifecycle)
            setIsPrimaryContractUpdateConfirmModalOpen(true);
        else setModalScreen(CONTRACT_LIFECYCLE_MODAL_SCREENS.CURRENT_PERIOD);
    };
    const handleSkipButtonClick = () => {
        syncFormState();
        setContractLifecycleSchedules([]);
        setSkipRenewalRules(true);
        if (shouldMarkAsPrimaryContract) {
            setIsPrimaryContractUpdateConfirmModalOpen(true);
        } else setIsSavingContract(true);
    };

    useEffect(() => {
        if (isSavingContract) saveHandler();
    }, [isSavingContract]);

    const determinePaymentEntityId = () => {
        if (shouldUpdatePaymentEntity) return null;

        return (
            account?.accountPaymentTerm?.paymentEntity
                ?.referencePaymentEntityId || null
        );
    };

    useEffect(() => {
        if (account)
            setReferencePaymentEntity(
                account?.accountPaymentTerm?.paymentEntity || null
            );
        else setReferencePaymentEntity(null);

        if (account?.contracts && account?.contracts.length > 0) {
            const allAreTerminated: boolean = account.contracts.every(
                contract =>
                    contract?.lifecycle &&
                    (contract.lifecycle.lifecycleStatus ===
                        AbacusContractLifecycleStatus.TERMINATED ||
                        contract.lifecycle.lifecycleStatus ===
                            AbacusContractLifecycleStatus.IN_COLLECTION_PERIOD)
            );
            setShouldUpdatePaymentEntity(allAreTerminated);
        } else setShouldUpdatePaymentEntity(true);

        if (!isSavingContract)
            setContract({
                ...contract,
                accountId,
                contractType: null,
                referenceSigningEntityId: null,
                runControllerId: null,
            });

        setContractLifecycleSchedule({
            ...contractLifecycleSchedule,
            collectionPeriodDetailInterval: null,
            collectionPeriodDetailType: CONTRACT_INTERVAL_TYPES.DAYS.value,
        });

        setHasCollectionPeriod(false);
    }, [account]);

    useEffect(() => {
        if (signingEntity?.referencePaymentEntity)
            setReferencePaymentEntity(signingEntity.referencePaymentEntity);
    }, [signingEntity]);

    useEffect(() => {
        setErrors({});
    }, [contract, contractLifecycleSchedule]);

    useEffect(() => {
        if (
            isFeaturePrimaryContractEnabled &&
            contract.contractType === CONTRACT_TYPES.DISTRIBUTION
        ) {
            let primaryContract =
                account?.contracts?.filter(
                    (existingContract: AbacusContract) =>
                        existingContract?.isPrimaryContract &&
                        existingContract?.contractType === contract.contractType
                ) || [];

            if (
                primaryContract[0]?.lifecycle?.lifecycleStatus ===
                AbacusContractLifecycleStatus.TERMINATED
            ) {
                setExistingPrimaryContract(primaryContract[0]);
                primaryContract = [];
            }

            if (!isEmpty(primaryContract)) {
                if (contract.isPrimaryContract) {
                    setShouldMarkAsPrimaryContract(true);
                    setShouldMarkAsPrimaryContractWithLifecycle(true);
                    setExistingPrimaryContract(primaryContract[0]);
                } else {
                    setShouldMarkAsPrimaryContract(false);
                    setShouldMarkAsPrimaryContractWithLifecycle(false);
                    setExistingPrimaryContract(null);
                }
            } else {
                setShouldMarkAsPrimaryContract(false);
                setShouldMarkAsPrimaryContractWithLifecycle(false);
            }
        }
    }, [contract.isPrimaryContract]);

    const renderGeneralNotes = () => {
        if (!shouldRenderGeneralNotesSection) {
            return (
                <Row>
                    <Col>
                        <Button
                            data-testid="addNotesButton"
                            variant="quartenary"
                            onClick={() =>
                                setShouldRenderGeneralNotesSection(true)
                            }
                        >
                            + Add Notes
                        </Button>
                    </Col>
                </Row>
            );
        } else {
            return (
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Add Notes (optional)</Form.Label>
                            <Form.Control
                                as="textarea"
                                placeholder="Enter Contract Summary Notes"
                                data-testid="generalNotesForm"
                                id="generalNotesForm"
                                onChange={handleGeneralNotesChange}
                                type="text"
                                maxLength={MAX_CHARACTERS}
                                value={contract.generalNote || ''}
                                rows={5}
                            />
                        </Form.Group>
                    </Col>
                </Row>
            );
        }
    };

    const renderCollectionPeriodSection = () => {
        if (contract.contractType === CONTRACT_TYPES.NEIGHBOURING_RIGHTS)
            return (
                <CollectionPeriod
                    contractLifecycleSchedule={contractLifecycleSchedule}
                    errors={errors!}
                    handleFormChange={handleCollectionPeriodChange}
                    isCollectionPeriodVisible={hasCollectionPeriod}
                    isDisabled={false}
                    setIsCollectionPeriodVisible={setHasCollectionPeriod}
                />
            );
    };

    const markContractAsPrimary = (existingContract: AbacusContract | null) => (
        <div>
            A primary {existingContract?.contractType} contract{' '}
            <b>
                {existingContract?.contractName} ({existingContract?.contractId}
                )
            </b>{' '}
            already exists for <b>{account?.accountName}</b> account. <br /> Do
            you want to make this new contract primary and set the existing one
            as non-primary?
        </div>
    );

    return (
        <Container
            className={cx('ContractLifecycleFullScreenModal-Container', {
                visible: isVisible,
            })}
        >
            <Form className="ContractLifecycleGeneralInformationScreen">
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Select Account</Form.Label>
                            <Row>
                                <Col sm={7}>{renderAccountSearch()}</Col>
                                <Col sm={5}>
                                    {referencePaymentEntity?.paymentEntityName && (
                                        <>
                                            <Row>
                                                <Col className="ContractLifecycleGeneralInformationScreen-AccountPaidBy-label">
                                                    <Label
                                                        testId="paidByLabel"
                                                        help={{
                                                            id: 'paidByHelpTooltip',
                                                            message:
                                                                PAID_BY_TOOLTIP_MSG,
                                                        }}
                                                        text="Paid By"
                                                    />
                                                </Col>
                                            </Row>
                                            <Row>
                                                <Col>
                                                    <span data-testid="paymentEntityName">
                                                        {
                                                            referencePaymentEntity?.paymentEntityName
                                                        }
                                                    </span>

                                                    {shouldUpdatePaymentEntity && (
                                                        <>
                                                            <Tooltip
                                                                testId="paidBySigningEntityTooltip"
                                                                id="paidBySigningEntityTooltip"
                                                                message={
                                                                    PAID_BY_SIGNING_ENTITY_TOOLTIP_MSG
                                                                }
                                                            >
                                                                <Highlight
                                                                    variant="info"
                                                                    testId="autoPopulatedHighlight"
                                                                    className="ContractLifecycleGeneralInformationScreen-AccountPaidBy-autofilled-text"
                                                                >
                                                                    Auto-Populated
                                                                </Highlight>
                                                            </Tooltip>
                                                        </>
                                                    )}
                                                </Col>
                                            </Row>
                                        </>
                                    )}
                                </Col>
                            </Row>
                            <span className="error">{errors?.accountId}</span>
                        </Form.Group>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Contract Name</Form.Label>
                            <Form.Control
                                data-testid="contractNameInput"
                                className={errors?.contractName ? 'error' : ''}
                                maxLength={180}
                                name="contractName"
                                placeholder="Enter Contract Name"
                                type="text"
                                value={contract.contractName || undefined}
                                onChange={(
                                    e: React.ChangeEvent<HTMLInputElement>
                                ) =>
                                    setContract({
                                        ...contract,
                                        [e.target.name]: sanitizeTextInput(
                                            e.target.value
                                        ),
                                    })
                                }
                            />
                            <span className="error">
                                {errors?.contractName}
                            </span>
                        </Form.Group>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Contract Type</Form.Label>
                            {isFeatureSingleSupplyChainCompanyCodesEnabled ? (
                                <ContractTypesDropdown
                                    className={
                                        errors?.contractType ? 'error' : ''
                                    }
                                    id="contractTypeSelect"
                                    isClearable={true}
                                    isDisabled={false}
                                    onChange={handleContractTypeChange}
                                    placeholder="Select Contract Type"
                                    removeOptions={['legacy_distribution']}
                                    testId="contractTypeSelect"
                                    value={contract.contractType || ''}
                                />
                            ) : (
                                <ContractTypeSelect
                                    className={
                                        errors?.contractType ? 'error' : ''
                                    }
                                    id="contractTypeSelect"
                                    isClearable={false}
                                    isDisabled={false}
                                    name="contractType"
                                    onChange={handleContractTypeChange}
                                    placeholder="Select Contract Type"
                                    removeOptions={['legacy_distribution']}
                                    testId="contractTypeSelect"
                                    value={contract.contractType || []}
                                />
                            )}
                            <span className="error">
                                {errors?.contractType}
                            </span>
                        </Form.Group>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Signing Entity</Form.Label>
                            {isFeatureSingleSupplyChainCompanyCodesEnabled ? (
                                <ReferenceSigningEntityDropdown
                                    className={
                                        errors?.referenceSigningEntityId
                                            ? 'error SigningEntity'
                                            : 'SigningEntity'
                                    }
                                    id="signingEntity"
                                    isClearable={true}
                                    isDisabled={!contract.accountId}
                                    onChange={(e: ListViewItem | undefined) => {
                                        setContract({
                                            ...contract,
                                            referenceSigningEntityId:
                                                e?.value || null,
                                            referenceSapProfitCenterId: null,
                                        });
                                    }}
                                    paymentEntityId={determinePaymentEntityId()}
                                    placeholder="Select Signing Entity"
                                    setSapProfitCenters={setSapProfitCenters}
                                    value={
                                        contract.referenceSigningEntityId ||
                                        null
                                    }
                                    testId="signingEntitySelect"
                                />
                            ) : (
                                <ReferenceSigningEntitySelect
                                    className={
                                        errors?.referenceSigningEntityId
                                            ? 'error SigningEntity'
                                            : 'SigningEntity'
                                    }
                                    id="signingEntity"
                                    isClearable={false}
                                    isDisabled={!contract.accountId}
                                    name="signingEntity"
                                    onChange={(e: any) => {
                                        setContract({
                                            ...contract,
                                            referenceSigningEntityId: e?.value,
                                        });
                                    }}
                                    paymentEntityId={determinePaymentEntityId()}
                                    placeholder="Select Signing Entity"
                                    value={
                                        contract.referenceSigningEntityId ||
                                        null
                                    }
                                    testId="signingEntitySelect"
                                />
                            )}

                            <span className="error">
                                {errors?.referenceSigningEntityId}
                            </span>
                        </Form.Group>
                    </Col>
                </Row>
                {isFeatureSingleSupplyChainCompanyCodesEnabled &&
                    contract.referenceSigningEntityId && (
                        <Row>
                            <Col>
                                <Form.Group>
                                    <Form.Label>Profit Center Name</Form.Label>
                                    <ReferenceSapProfitCenterDropdown
                                        className={
                                            errors?.referenceSapProfitCenterId
                                                ? 'error SapProfitCenter'
                                                : 'SapProfitCenter'
                                        }
                                        id="sapProfitCenter"
                                        isClearable={true}
                                        isDisabled={
                                            !contract.referenceSigningEntityId
                                        }
                                        name="sapProfitCenter"
                                        onChange={(
                                            e: ListViewItem | undefined
                                        ) => {
                                            setContract({
                                                ...contract,
                                                referenceSapProfitCenterId:
                                                    e?.value || null,
                                            });
                                        }}
                                        placeholder="Select"
                                        value={
                                            contract.referenceSapProfitCenterId ||
                                            null
                                        }
                                        sapProfitCenters={sapProfitCenters}
                                        signingEntityId={
                                            contract.referenceSigningEntityId
                                        }
                                        testId="sapProfitCenterSelect"
                                    />
                                    <span className="error">
                                        {errors?.referenceSapProfitCenterId}
                                    </span>
                                </Form.Group>
                            </Col>
                        </Row>
                    )}
                <Row>
                    <Col>
                        <Form.Group>
                            <div>
                                <Form.Label>
                                    Execution Date &nbsp;
                                    <span>(optional)</span> &nbsp;
                                    <Tooltip
                                        id="executionDateTooltip"
                                        message={TOOLTIP_EXECUTION_DATE}
                                        placement="right"
                                        testId="executionDateTooltip"
                                    >
                                        <GlyphIcon name="info" size={12} />
                                    </Tooltip>
                                </Form.Label>
                            </div>
                            <DatePicker
                                onChange={date => {
                                    setContract({
                                        ...contract,
                                        executionDate: date || null,
                                    });
                                }}
                                placeholder={YYYY_MM_DD}
                                selectedValue={contract.executionDate || ''}
                                testId="executionDatePicker"
                            />
                        </Form.Group>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Run Controller</Form.Label>
                            {isFeatureSingleSupplyChainCompanyCodesEnabled ? (
                                <RunControllerDropdown
                                    accountId={contract.accountId || ''}
                                    className={
                                        errors?.runControllerId
                                            ? 'error'
                                            : undefined
                                    }
                                    contractType={contract.contractType || ''}
                                    isDisabled={!contract.contractType}
                                    isClearable={true}
                                    onChange={(e: ListViewItem | undefined) => {
                                        setContract({
                                            ...contract,
                                            runControllerId: e?.value || null,
                                        });
                                    }}
                                    testId="runControllerSelect"
                                    value={contract?.runControllerId || ''}
                                />
                            ) : (
                                <RunControllerSelect
                                    accountId={contract.accountId || ''}
                                    className={
                                        errors?.runControllerId
                                            ? 'error'
                                            : undefined
                                    }
                                    contractType={contract.contractType || ''}
                                    disabled={!contract.contractType}
                                    onChange={e => {
                                        setContract({
                                            ...contract,
                                            runControllerId: e?.value,
                                        });
                                    }}
                                    testId="runControllerSelect"
                                    value={contract.runControllerId || ''}
                                />
                            )}
                            <span className="error">
                                {errors?.runControllerId}
                            </span>
                        </Form.Group>
                    </Col>
                </Row>
                {isFeaturePrimaryContractEnabled &&
                    contract.contractType === CONTRACT_TYPES.DISTRIBUTION && (
                        <>
                            <Row>
                                <Col className="PrimaryContractSwitchField">
                                    <Form.Group>
                                        <Switch
                                            id="isPrimaryContract"
                                            label="Is Primary Contract"
                                            name="isPrimaryContract"
                                            onChange={() => {
                                                setContract({
                                                    ...contract,
                                                    isPrimaryContract:
                                                        !contract.isPrimaryContract,
                                                });
                                            }}
                                            checked={contract.isPrimaryContract}
                                        />
                                    </Form.Group>
                                    <span className="PrimaryContractSwitchField-Optional-Text">
                                        (optional)
                                    </span>
                                </Col>
                            </Row>
                            <Modal
                                className="PrimaryContractUpdateConfirmModal"
                                title="Set New Contract as Primary"
                                confirmTitle="Apply Change"
                                testId="primaryContractUpdateConfirmModal"
                                isOpen={isPrimaryContractUpdateConfirmModalOpen}
                                onRequestClose={() => {
                                    setIsPrimaryContractUpdateConfirmModalOpen(
                                        false
                                    );
                                }}
                                confirmDisabled={isSavingContract}
                                onConfirm={() => {
                                    if (skipRenewalRules) {
                                        setIsPrimaryContractUpdateConfirmModalOpen(
                                            false
                                        );
                                        setIsSavingContract(true);
                                    } else {
                                        setIsPrimaryContractUpdateConfirmModalOpen(
                                            false
                                        );
                                        setModalScreen(
                                            CONTRACT_LIFECYCLE_MODAL_SCREENS.CURRENT_PERIOD
                                        );
                                        setShouldMarkAsPrimaryContractWithLifecycle(
                                            false
                                        );
                                    }
                                }}
                            >
                                <div className="ContractLifecycleFullScreenModal-PrimaryContractUpdateText">
                                    {markContractAsPrimary(
                                        existingPrimaryContract
                                    )}
                                </div>
                            </Modal>
                        </>
                    )}
                {renderCollectionPeriodSection()}
                {renderGeneralNotes()}
            </Form>
            <div className="ContractLifecycleFullScreenModal-Footer">
                <Row>
                    <Col className="ContractLifecycleFullScreenModal-NextButtonCol">
                        <Button
                            variant="secondary"
                            data-testid="skipButton"
                            disabled={
                                isNextButtonDisabled() || isSavingContract
                            }
                            onClick={handleSkipButtonClick}
                        >
                            Skip Renewal And Create Contract
                        </Button>
                        <Button
                            variant="primary"
                            data-testid="nextButton"
                            disabled={
                                isNextButtonDisabled() || isSavingContract
                            }
                            onClick={handleNextButtonClick}
                        >
                            Continue to Renewal Terms
                        </Button>
                    </Col>
                </Row>
            </div>
        </Container>
    );
};
