import {
    Alert,
    DatePicker,
    Field,
    MarketSelector,
    MultiSelect,
    Radio,
    Select,
    Sidecar,
    Stepper,
} from '@theorchard/suite-components';
import cx from 'classnames';
import dayjs from 'dayjs';
import { remove, uniqBy } from 'lodash';
import React, { useEffect, useState } from 'react';
import { useIsYouTubeFingerprintRulesEnabled } from 'shared/features';
import { TimeRule } from 'src/components/fingerprintRulesOAPanel/deliveryRules/delivery-rules';
import { PolicyType } from 'src/types';
import { isDateRangeOverlaping, validateRules } from 'src/utils/validation';
import type { CountryOption, Step } from '@theorchard/suite-components';
import type { FC } from 'react';
import type {
    DropdownCountryInfo,
    FingerprintRule,
    FingerprintRuleInput,
    Territory,
} from 'src/types';

const CLASS_NAME = 'UpdatedAddRule';

export interface EditRowData {
    territories: string[];
    service: DropdownOption;
    policy: DropdownOption;
    startDate: string;
    endDate: string;
}

enum MAPPED_POLICY {
    Monetize = 'monetize',
    Block = 'block_access',
    'Carve-out' = 'carveout',
}

const SERVICE_OPTIONS = [
    { value: 'TikTok', label: 'TikTok' },
    { value: 'YouTube', label: 'YouTube' },
];

const POLICY_OPTIONS = [
    { value: 'Monetize', label: 'Monetize' },
    { value: 'Block', label: 'Block' },
    { value: 'Carve-out', label: 'Carve-out' },
];

export interface UpdatedAddRuleProps {
    title: string;
    isOpen: boolean;
    onClose: () => void;
    onConfirm: (
        rules: FingerprintRuleInput[],
        timeFilter: TimeRule | null
    ) => void;
    territories: Territory[] | undefined;
    higherLevelRules: FingerprintRule[];
    currentRules: FingerprintRule[];
    editRowData?: EditRowData;
    showSetUpSelection?: boolean;
}

interface DropdownOption {
    value: string;
}

const RADIO_PRESELECTION_CARVEOUT = 'preselection_carveout';
const RADIO_PRESELECTION_CUSTOM = 'preselection_custom';

const getServiceStepContent = (
    isYoutubeFingerprintRulesEnabled: boolean,
    servicesOption: DropdownOption[],
    handleServiceChange: (events: { value: string; label: string }[]) => void,
    editRowData?: EditRowData
) => {
    return (
        <div className={cx(`${CLASS_NAME}-rule-data-service`)}>
            <MultiSelect
                placeholder={$t(
                    'fingerprintRules.updatedAddRule.dropdown.service.placeholder'
                )}
                selectedValue={
                    editRowData ? [editRowData.service] : servicesOption
                }
                options={SERVICE_OPTIONS}
                onChange={handleServiceChange}
                disabled={!!editRowData || !isYoutubeFingerprintRulesEnabled}
                testId="service-dropdown"
            />
            {!isYoutubeFingerprintRulesEnabled && (
                <p className={cx(`${CLASS_NAME}-rule-data-warning`)}>
                    {$t(
                        'fingerprintRules.updatedAddRule.dropdown.service.note'
                    )}
                </p>
            )}
        </div>
    );
};

const getCountryStepContent = (
    dropdownCountries: DropdownCountryInfo[],
    countriesOption: string[],
    handleCountryChange: (events: CountryOption[]) => void,
    isDisabled: boolean,
    editRowData?: EditRowData
) => {
    return (
        <div className={cx(`${CLASS_NAME}-rule-data`)}>
            <div className={cx(`${CLASS_NAME}-rule-data-country`)}>
                <MarketSelector
                    selectedValue={
                        editRowData ? editRowData.territories : countriesOption
                    }
                    onChange={handleCountryChange}
                    countries={dropdownCountries}
                    testId="country-dropdown"
                    disabled={isDisabled || !!editRowData}
                    sectionGroupSelect
                />
            </div>
        </div>
    );
};

const getRuleStepContent = (
    isNotCarveoutSelected: boolean,
    policyOption: DropdownOption | undefined,
    handlePolicyChange: (
        event: { value: string; label: string } | undefined
    ) => void,
    isDisabled: boolean,
    startDateOption: string,
    handleStartDateChange: (event: string | undefined) => void,
    endDateOption: string,
    handleEndDateChange: (event: string | undefined) => void,
    editRowData?: EditRowData
) => {
    // because we're treating the end date as exclusive (not inclusive)
    // e.g. a single-day policy is now achieved by picking the day
    // the policy is supposed to go into effect as the start date, and the day after as the end date
    const startDatePlusOne = startDateOption
        ? dayjs(startDateOption).add(1, 'day').format('YYYY-MM-DD')
        : '';

    const endDateCustomDateRange = startDateOption
        ? {
              start: startDatePlusOne,
              end: dayjs(
                  new Date(new Date().getFullYear() + 10, 11, 31)
              ).format('YYYY-MM-DD'),
          }
        : undefined;

    return (
        <div>
            <div className={cx(`${CLASS_NAME}-rule-data-policy`)}>
                <Select
                    placeholder={$t(
                        'fingerprintRules.updatedAddRule.dropdown.policy.placeholder'
                    )}
                    selectedValue={
                        editRowData ? editRowData.policy : policyOption
                    }
                    options={POLICY_OPTIONS}
                    onChange={handlePolicyChange}
                    disabled={!!editRowData || isDisabled}
                    testId="policy-dropdown"
                    hideFilter
                />
            </div>
            {isNotCarveoutSelected && (
                <div className={cx(`${CLASS_NAME}-rule-data-dates`)}>
                    <Field
                        className={cx(`${CLASS_NAME}-rule-data-title`)}
                        labelText={$t(
                            'fingerprintRules.updatedAddRule.dropdown.date.start'
                        )}
                        controlId="startDate"
                    >
                        <DatePicker
                            selectedValue={startDateOption}
                            onChange={handleStartDateChange}
                            disabled={editRowData ? false : !policyOption}
                            testId="start-date-picker"
                        />
                    </Field>
                    <Field
                        className={cx(
                            `${CLASS_NAME}-rule-data-title ${CLASS_NAME}-rule-data-dates-end`
                        )}
                        labelText={$t(
                            'fingerprintRules.updatedAddRule.dropdown.date.end'
                        )}
                        controlId="endDate"
                    >
                        <DatePicker
                            customDateRange={endDateCustomDateRange}
                            selectedValue={endDateOption}
                            onChange={handleEndDateChange}
                            disabled={editRowData ? false : !policyOption}
                            testId="end-date-picker"
                        />
                    </Field>
                </div>
            )}
        </div>
    );
};

const renderAlertText = (
    isCreateRuleValidation: boolean,
    isHigherLevelExistingRule: boolean,
    createRuleValidationMessage: string
) => {
    if (isCreateRuleValidation) {
        let errorMessage: string = '';
        switch (createRuleValidationMessage) {
            case 'duplicateCarveout':
                errorMessage = $t(
                    'fingerprintRules.updatedAddRule.alert.validation.duplicateCarveout'
                );
                break;
            case 'conflictingRule':
                errorMessage = $t(
                    'fingerprintRules.updatedAddRule.alert.validation.conflictingRule'
                );
                break;
            case 'nonLastRuleEndDate':
                errorMessage = $t(
                    'fingerprintRules.updatedAddRule.alert.validation.nonLastRuleEndDate'
                );
                break;
            case 'conflictingDates':
                errorMessage = $t(
                    'fingerprintRules.updatedAddRule.alert.validation.conflictingDates'
                );
                break;
            case 'duplicateRules':
                errorMessage = $t(
                    'fingerprintRules.updatedAddRule.alert.validation.duplicateRules'
                );
                break;
        }

        return (
            <div>
                <p>{errorMessage}</p>
            </div>
        );
    }
    if (isHigherLevelExistingRule) {
        return (
            <div>
                <p>
                    {$t(
                        'fingerprintRules.updatedAddRule.alert.existingHigherRule.firstLine'
                    )}
                </p>
                <p>
                    {$t(
                        'fingerprintRules.updatedAddRule.alert.existingHigherRule.secondLine'
                    )}
                </p>
            </div>
        );
    }
};

const formatCurrentRules = (
    rules: FingerprintRule[]
): FingerprintRuleInput[] => {
    return rules.map(r => {
        const policy =
            Object.keys(PolicyType)[
                Object.values(PolicyType).indexOf(r.policy as PolicyType)
            ];
        const service = r.service.toLowerCase();
        const territory = r.territory;
        let startDate = (r.startDate as string) || null;
        if (!startDate || startDate === '-') startDate = null;
        let endDate = (r.endDate as string) || null;
        if (!endDate || endDate === '-') endDate = null;
        return {
            policy,
            service,
            territory,
            start: startDate
                ? dayjs(startDate).format('YYYY-MM-DD') + 'T00:00:00+00:00'
                : null,
            end: endDate
                ? dayjs(endDate).format('YYYY-MM-DD') + 'T00:00:00+00:00'
                : null,
        };
    });
};

const UpdatedAddRule: FC<UpdatedAddRuleProps> = ({
    title,
    isOpen,
    onClose,
    onConfirm,
    territories,
    higherLevelRules,
    currentRules,
    editRowData,
    showSetUpSelection,
}) => {
    const isYoutubeFingerprintRulesEnabled =
        useIsYouTubeFingerprintRulesEnabled();

    const [radioPreselectionOption, setRadioPreselectionOption] = useState<
        string | null
    >(null);
    const [policyOption, setPolicyOption] = useState<
        DropdownOption | undefined
    >(showSetUpSelection ? POLICY_OPTIONS[0] : undefined);
    const [countriesOption, setCountriesOption] = useState<string[]>([]);
    const [servicesOption, setServicesOption] = useState<DropdownOption[]>(
        !isYoutubeFingerprintRulesEnabled ? [SERVICE_OPTIONS[0]] : []
    );
    const [startDateOption, setStartDateOption] = useState<string>('');
    const [endDateOption, setEndDateOption] = useState<string>('');
    const [createRuleValidationMessage, setCreateRuleValidationMessage] =
        useState<string>('');
    const [showHigherLevelExistingRule, setShowHigherLevelExistingRule] =
        useState(false);
    const [showCreateRuleValidation, setShowCreateRuleValidation] =
        useState(false);

    const isNotCarveoutSelected = editRowData
        ? editRowData?.policy.value !== POLICY_OPTIONS[2].value
        : !!policyOption?.value &&
          policyOption?.value !== POLICY_OPTIONS[2].value;

    const dropdownCountries =
        territories?.map(country => {
            const carvedOut = currentRules.filter(
                r =>
                    r.territory === country.territoryCodeA2 &&
                    r.policy === PolicyType.carveout &&
                    (r.service.toLowerCase() === 'tiktok' ||
                        (isYoutubeFingerprintRulesEnabled
                            ? r.service.toLowerCase() === 'youtube'
                            : false))
            );
            const isRestricted = carvedOut.length > 0;
            return {
                value: country.territoryCodeA2,
                subtitle: isRestricted
                    ? 'This country is already restricted for one or more services'
                    : '',
                continent: country.continent,
                disabled: isRestricted,
            };
        }) ?? [];

    useEffect(() => {
        if (editRowData) {
            setStartDateOption(editRowData.startDate);
            setEndDateOption(editRowData.endDate);
        }
    }, [editRowData]);

    useEffect(() => {
        findExistingRule();
    }, [
        servicesOption,
        countriesOption,
        policyOption,
        startDateOption,
        endDateOption,
    ]);

    useEffect(() => {
        if (
            servicesOption.length > 0 &&
            countriesOption.length > 0 &&
            policyOption &&
            (!isNotCarveoutSelected || startDateOption)
        )
            validateRulesToCreate();
    }, [
        servicesOption,
        countriesOption,
        policyOption,
        startDateOption,
        endDateOption,
        isNotCarveoutSelected,
    ]);

    const isCarveoutPreselect =
        showSetUpSelection &&
        radioPreselectionOption === RADIO_PRESELECTION_CARVEOUT;
    const isCustomPreselect =
        showSetUpSelection &&
        radioPreselectionOption === RADIO_PRESELECTION_CUSTOM;

    const extractRulesToCreate = (): FingerprintRuleInput[] => {
        const rulesToCreate = [] as FingerprintRuleInput[];
        let policy = '',
            startDate = '',
            endDate = '';

        if (policyOption && policyOption.value) {
            policy =
                MAPPED_POLICY[policyOption.value as keyof typeof MAPPED_POLICY];
        }

        if (startDateOption) startDate = startDateOption + 'T00:00:00+00:00';
        if (endDateOption) endDate = endDateOption + 'T00:00:00+00:00';

        countriesOption.forEach(t => {
            servicesOption.forEach(s => {
                rulesToCreate.push({
                    policy: policy,
                    service:
                        s.value.toLowerCase() === 'global'
                            ? '*'
                            : s.value.toLowerCase(),
                    territory: t.toLowerCase() === 'global' ? '*' : t,
                    start: startDate ? startDate : null,
                    end: endDate ? endDate : null,
                });
            });
        });

        return rulesToCreate;
    };

    const validateRulesToCreate = () => {
        const rulesToCreate = extractRulesToCreate();
        const formattedCurrentRules = formatCurrentRules(currentRules);
        const validated = validateRules(
            formattedCurrentRules.concat(rulesToCreate)
        );
        if (!validated.isValid) {
            setShowCreateRuleValidation(true);
            setCreateRuleValidationMessage(validated.message);
        } else setShowCreateRuleValidation(false);
    };

    const isExistingRuleFound = (rules: FingerprintRuleInput[]): boolean => {
        const rulesToCreate = extractRulesToCreate();
        let foundExistingRule = false;
        for (
            let indexCurrent = 0;
            indexCurrent < rules.length;
            indexCurrent++
        ) {
            const currentRule = rules[indexCurrent];
            const { policy, service, territory, start, end } = currentRule;
            const isGlobalTerritory = territory === '*';
            for (
                let indexCreate = 0;
                indexCreate < rulesToCreate.length;
                indexCreate++
            ) {
                const createRule = rulesToCreate[indexCreate];
                if (isGlobalTerritory) {
                    //Check exact match in global context
                    if (
                        createRule.policy === policy &&
                        createRule.service === service &&
                        createRule.start === start &&
                        createRule.end === end
                    ) {
                        foundExistingRule = true;
                        break;
                    }
                    //Check match within date range
                    if (
                        createRule.policy === policy &&
                        createRule.service === service
                    ) {
                        if (start && createRule.start) {
                            const isDateBetween = isDateRangeOverlaping(
                                start,
                                end,
                                createRule.start,
                                createRule.end
                            );
                            if (isDateBetween) {
                                foundExistingRule = true;
                                break;
                            }
                        }
                    }
                } else {
                    //Check exact match
                    if (
                        createRule.policy === policy &&
                        createRule.service === service &&
                        createRule.territory === territory &&
                        createRule.start === start &&
                        createRule.end === end
                    ) {
                        foundExistingRule = true;
                        break;
                    }
                    //Check match within date range
                    if (
                        createRule.policy === policy &&
                        createRule.service === service &&
                        createRule.territory === territory
                    ) {
                        if (start && createRule.start) {
                            const isDateBetween = isDateRangeOverlaping(
                                start,
                                end,
                                createRule.start,
                                createRule.end
                            );
                            if (isDateBetween) {
                                foundExistingRule = true;
                                break;
                            }
                        }
                    }
                }
            }
        }

        return foundExistingRule;
    };

    const findExistingRule = () => {
        const formattedHigherLevelRules = formatCurrentRules(higherLevelRules);
        const foundHigherLevelExistingRule = isExistingRuleFound(
            formattedHigherLevelRules
        );
        if (foundHigherLevelExistingRule) {
            setShowHigherLevelExistingRule(true);
        } else {
            setShowHigherLevelExistingRule(false);
        }
    };

    const handleServiceChange = (
        events: { value: string; label: string }[]
    ) => {
        setServicesOption(events);
    };

    const handleCountryChange = (events: CountryOption[]) => {
        setCountriesOption(events.map(e => e.value));
    };

    const handlePolicyChange = (
        event: { value: string; label: string } | undefined
    ) => {
        setPolicyOption(event);
    };

    const handleStartDateChange = (event: string | undefined) => {
        setStartDateOption(event || '');
    };

    const handleEndDateChange = (event: string | undefined) => {
        setEndDateOption(event || '');
    };

    const handleClose = () => {
        setCountriesOption([]);
        // I'm not completely removing this in case we're having more than one service in the future
        // setServicesOption([]);
        setPolicyOption(undefined);
        setStartDateOption('');
        setEndDateOption('');
        setShowCreateRuleValidation(false);
        setShowHigherLevelExistingRule(false);

        return onClose();
    };

    const isSaveDisabled = () => {
        if (isCarveoutPreselect) return false;

        if (editRowData) {
            if (!startDateOption) return true;
            return showCreateRuleValidation;
        }

        if (isNotCarveoutSelected) {
            return !(
                servicesOption.length > 0 &&
                policyOption &&
                countriesOption.length > 0 &&
                startDateOption &&
                (!isNotCarveoutSelected || startDateOption) &&
                !showCreateRuleValidation
            );
        } else {
            return !(
                servicesOption.length > 0 &&
                countriesOption.length > 0 &&
                policyOption &&
                !showCreateRuleValidation
            );
        }
    };

    const handlePreselectCarveoutSave = () => {
        const startDate = `${
            new Date().toISOString().split('T')[0]
        }T00:00:00+00:00`;
        const formattedCurrentRules = formatCurrentRules(currentRules);
        const rulesToCreate = dropdownCountries.map(t => ({
            policy: t.value === 'RU' ? 'carveout' : 'monetize',
            service: 'tiktok',
            territory: t.value,
            start: t.value === 'RU' ? null : startDate,
            end: null,
        }));

        if (isYoutubeFingerprintRulesEnabled) {
            const youtubeRulesToCreate = dropdownCountries.map(t => ({
                policy: t.value === 'RU' ? 'carveout' : 'monetize',
                service: 'youtube',
                territory: t.value,
                start: t.value === 'RU' ? null : startDate,
                end: null,
            }));
            rulesToCreate.push(...youtubeRulesToCreate);
        }

        const allRules = uniqBy(
            formattedCurrentRules.concat(rulesToCreate),
            r => r.policy + r.service + r.territory + r.start + r.end
        );
        return onConfirm(allRules, TimeRule.active);
    };

    const handleSaveRule = () => {
        if (isCarveoutPreselect) {
            return handlePreselectCarveoutSave();
        }

        const formattedCurrentRules = formatCurrentRules(currentRules);
        const rulesToCreate = extractRulesToCreate();
        const formattedRules = uniqBy(
            formattedCurrentRules.concat(rulesToCreate),
            r => r.policy + r.service + r.territory + r.start + r.end
        );

        setCountriesOption([]);
        // I'm not completely removing this in case we're having more than one service in the future
        // setServicesOption([]);
        setPolicyOption(undefined);
        setStartDateOption('');
        setEndDateOption('');

        // pre-selecting time filter
        const timeFilter =
            rulesToCreate[0].start &&
            new Date(rulesToCreate[0].start) > new Date()
                ? TimeRule.scheduled
                : TimeRule.active;

        return onConfirm(formattedRules, timeFilter);
    };

    const handleEditRule = () => {
        if (editRowData) {
            const editService =
                editRowData.service.value.toLowerCase() === 'global'
                    ? '*'
                    : editRowData.service.value;
            const editPolicy = editRowData.policy.value;
            const editTerritories = editRowData.territories.map(t =>
                t.toLowerCase() === 'global' ? '*' : t
            );
            const editStartDate = editRowData.startDate;
            const editEndDate = editRowData.endDate;
            const rulesToSave = [...currentRules];
            //Delete exisitng rule based on edit data
            remove(rulesToSave, r => {
                let startDate = '',
                    endDate = '';
                if (r.startDate && r.startDate !== '-') {
                    startDate = dayjs(r.startDate).format('YYYY-MM-DD');
                }
                if (r.endDate && r.endDate !== '-') {
                    endDate = dayjs(r.endDate).format('YYYY-MM-DD');
                }
                if (
                    r.service === editService &&
                    r.policy === editPolicy &&
                    startDate === editStartDate &&
                    endDate === editEndDate &&
                    editTerritories.includes(r.territory)
                ) {
                    return true;
                } else false;
            });

            const formattedRulesToSave = formatCurrentRules(rulesToSave);
            let startDate = '',
                endDate = '';

            const policy =
                Object.keys(PolicyType)[
                    Object.values(PolicyType).indexOf(
                        editRowData.policy.value as PolicyType
                    )
                ];

            if (startDateOption)
                startDate = startDateOption + 'T00:00:00+00:00';
            if (endDateOption) endDate = endDateOption + 'T00:00:00+00:00';

            //Re-create rule with new dates
            editRowData.territories.forEach(t => {
                formattedRulesToSave.push({
                    policy: policy,
                    service:
                        editRowData.service.value.toLowerCase() === 'global'
                            ? '*'
                            : editRowData.service.value.toLowerCase(),
                    territory: t.toLowerCase() === 'global' ? '*' : t,
                    start: startDate ? startDate : null,
                    end: endDate ? endDate : null,
                });
            });

            setCountriesOption([]);
            // I'm not completely removing this in case we're having more than one service in the future
            // setServicesOption([]);
            setPolicyOption(undefined);
            setStartDateOption('');
            setEndDateOption('');

            return onConfirm(formattedRulesToSave, null);
        }
    };

    const steps: Step[] = [
        {
            icon: {
                glyphIcon: 'circle',
                variant: 'neutral',
            },
            title: $t('fingerprintRules.updatedAddRule.dropdown.service.title'),
            body: getServiceStepContent(
                isYoutubeFingerprintRulesEnabled,
                servicesOption,
                handleServiceChange,
                editRowData
            ),
        },
        {
            icon: {
                glyphIcon: 'circle',
                variant: 'neutral',
            },
            title: $t('fingerprintRules.updatedAddRule.dropdown.country.title'),
            body: getCountryStepContent(
                dropdownCountries,
                countriesOption,
                handleCountryChange,
                servicesOption.length === 0,
                editRowData
            ),
        },
        {
            icon: {
                glyphIcon: 'circle',
                variant: 'neutral',
            },
            title: $t('fingerprintRules.updatedAddRule.dropdown.policy.title'),
            body: getRuleStepContent(
                isNotCarveoutSelected,
                policyOption,
                handlePolicyChange,
                countriesOption.length === 0 || servicesOption.length === 0,
                startDateOption,
                handleStartDateChange,
                endDateOption,
                handleEndDateChange,
                editRowData
            ),
        },
    ];

    return (
        <Sidecar
            className={cx(`${CLASS_NAME}-sidecar`)}
            title={title}
            isOpen={isOpen}
            onRequestClose={handleClose}
            onConfirm={editRowData ? handleEditRule : handleSaveRule}
            confirmTitle={$t('fingerprintRules.updatedAddRule.saveTitle')}
            confirmDisabled={isSaveDisabled()}
            testId="sidecar"
        >
            <div className={cx(`${CLASS_NAME}-body`)}>
                {showSetUpSelection && (
                    <div className={`${CLASS_NAME}-setup-selection`}>
                        <div
                            className={`${CLASS_NAME}-setup-selection-description`}
                        >
                            {$t(
                                'fingerprintRules.updatedAddRule.setupSelectionRadio.description'
                            )}
                        </div>
                        <div className={`${CLASS_NAME}-setup-selection-title`}>
                            {$t(
                                'fingerprintRules.updatedAddRule.setupSelectionRadio.title'
                            )}
                        </div>
                        <Radio
                            className={`${CLASS_NAME}-setup-selection-radio-option`}
                            onClick={() =>
                                setRadioPreselectionOption(
                                    RADIO_PRESELECTION_CARVEOUT
                                )
                            }
                            label={
                                isYoutubeFingerprintRulesEnabled
                                    ? $t(
                                          'fingerprintRules.updatedAddRule.setupSelectionRadio.carveoutAllServices'
                                      )
                                    : $t(
                                          'fingerprintRules.updatedAddRule.setupSelectionRadio.carveout'
                                      )
                            }
                            name="radioPreselection"
                            data-testid="radioPreselectionCarveout"
                            testId="radioPreselectionCarveout"
                            id="radioPreselectionCarveout"
                        />
                        <Radio
                            className={`${CLASS_NAME}-setup-selection-radio-option ${CLASS_NAME}-setup-selection-radio-second-option`}
                            onClick={() =>
                                setRadioPreselectionOption(
                                    RADIO_PRESELECTION_CUSTOM
                                )
                            }
                            label={$t(
                                'fingerprintRules.updatedAddRule.setupSelectionRadio.custom'
                            )}
                            name="radioPreselection"
                            data-testid="radioPreselectionCustom"
                            testId="radioPreselectionCustom"
                            id="radioPreselectionCustom"
                        />
                    </div>
                )}

                {(!showSetUpSelection || isCustomPreselect) && (
                    <>
                        {showSetUpSelection && (
                            <hr className={cx(`${CLASS_NAME}-hr`)} />
                        )}
                        <Stepper layout="vertical" steps={steps} />
                    </>
                )}

                {(showHigherLevelExistingRule || showCreateRuleValidation) && (
                    <div className={cx(`${CLASS_NAME}-alert`)}>
                        <Alert
                            text={renderAlertText(
                                showCreateRuleValidation,
                                showHigherLevelExistingRule,
                                createRuleValidationMessage
                            )}
                            variant={
                                showCreateRuleValidation ? 'error' : 'warn'
                            }
                        />
                    </div>
                )}
            </div>
        </Sidecar>
    );
};

export default UpdatedAddRule;
