import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import InputAdornment from "@mui/material/InputAdornment";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { IconButton } from "@/shared/ui/IconButton.jsx";
import { JsonEditorField } from "@/shared/ui/JsonEditorField.jsx";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import styles from "@/features/policy-config/policy-config.module.css";

const agentPeriods = [["rolling_30d", "rolling_30d"]];
const bdPeriods = [["utc_calendar_month", "utc_calendar_month"]];
const gameInvitePeriods = [["rolling_30d", "rolling_30d"]];
const taskAssets = [
    ["POINT", "POINT"],
    ["COIN", "COIN"],
];

export function PolicyRuleEditorDrawer({ page }) {
    const saving = page.loadingAction === "template-save";
    const disabled = saving || !page.abilities.canSaveTemplate;
    const form = page.templateForm;

    return (
        <SideDrawer
            actions={
                <>
                    <Button disabled={saving} onClick={page.closeTemplateDrawer}>
                        取消
                    </Button>
                    <Button disabled={disabled} type="submit" variant="primary">
                        保存模板版本
                    </Button>
                </>
            }
            as="form"
            className={styles.ruleDrawer}
            contentClassName={styles.drawerBody}
            open={page.templateDrawerOpen}
            title={page.editingTemplate ? "编辑收益政策模板" : "新增收益政策模板"}
            width="wide"
            onClose={saving ? undefined : page.closeTemplateDrawer}
            onSubmit={page.submitTemplate}
        >
            <TemplateBaseFields disabled={disabled} form={form} setForm={page.setTemplateForm} />
            <GlobalRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <HostRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <AgentRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <BDRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <ManagerRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <CoinSellerRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <TaskAndGameRuleSection disabled={disabled} form={form.rule} setForm={page.setTemplateForm} />
            <JsonEditorField
                disabled={disabled}
                label="高级 JSON"
                minRows={12}
                value={form.rule.rawJson}
                onChange={(rawJson) => updateRule(page.setTemplateForm, { rawJson })}
            />
        </SideDrawer>
    );
}

function TemplateBaseFields({ disabled, form, setForm }) {
    const patch = (value) => setForm((current) => ({ ...current, ...value }));
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>模板基础</h3>
            </div>
            <div className={styles.formGrid}>
                <TextField
                    required
                    disabled={disabled}
                    label="模板名称"
                    size="small"
                    value={form.name}
                    onChange={(event) => patch({ name: event.target.value })}
                />
                <TextField
                    required
                    disabled={disabled}
                    label="模板编码"
                    size="small"
                    value={form.templateCode}
                    onChange={(event) => patch({ templateCode: event.target.value })}
                />
                <TextField
                    required
                    disabled={disabled}
                    label="模板版本"
                    size="small"
                    value={form.templateVersion}
                    onChange={(event) => patch({ templateVersion: event.target.value })}
                />
                <TextField
                    select
                    disabled={disabled}
                    label="状态"
                    size="small"
                    value={form.status}
                    onChange={(event) => patch({ status: event.target.value })}
                >
                    <MenuItem value="active">启用</MenuItem>
                    <MenuItem value="disabled">停用</MenuItem>
                </TextField>
                <TextField
                    className={styles.fieldWide}
                    disabled={disabled}
                    label="说明"
                    maxRows={3}
                    multiline
                    size="small"
                    value={form.description}
                    onChange={(event) => patch({ description: event.target.value })}
                />
            </div>
        </section>
    );
}

function GlobalRuleSection({ disabled, form, setForm }) {
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>全局口径</h3>
            </div>
            <div className={styles.formGrid}>
                <NumberField
                    disabled={disabled}
                    label="POINT/USD"
                    value={form.pointsPerUsd}
                    onChange={(pointsPerUsd) => updateRule(setForm, { pointsPerUsd })}
                />
                <NumberField
                    disabled={disabled}
                    label="Google 金币/USD"
                    value={form.googleCoinPerUsd}
                    onChange={(googleCoinPerUsd) => updateRule(setForm, { googleCoinPerUsd })}
                />
                <SwitchField
                    checked={form.allowSelfBrushing}
                    disabled={disabled}
                    label="允许自刷"
                    onChange={(allowSelfBrushing) => updateRule(setForm, { allowSelfBrushing })}
                />
            </div>
        </section>
    );
}

function HostRuleSection({ disabled, form, setForm }) {
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>主播收益</h3>
            </div>
            <div className={styles.formGrid}>
                <NumberField
                    disabled={disabled}
                    label="主播收益比例"
                    suffix="%"
                    value={form.host.pointRatioPercent}
                    onChange={(pointRatioPercent) => updateSection(setForm, "host", { pointRatioPercent })}
                />
                <NumberField
                    disabled={disabled}
                    label="Agency 分成比例"
                    suffix="%"
                    value={form.agency.pointRatioPercent}
                    onChange={(pointRatioPercent) => updateSection(setForm, "agency", { pointRatioPercent })}
                />
                <NumberField
                    disabled={disabled}
                    label="最低提现积分"
                    value={form.host.minimumWithdrawPoints}
                    onChange={(minimumWithdrawPoints) => updateSection(setForm, "host", { minimumWithdrawPoints })}
                />
                <NumberField
                    disabled={disabled}
                    label="提现手续费"
                    suffix="bps"
                    value={form.host.withdrawFeeBps}
                    onChange={(withdrawFeeBps) => updateSection(setForm, "host", { withdrawFeeBps })}
                />
                <SwitchField
                    checked={form.host.affectsRoomHeat}
                    disabled={disabled}
                    label="影响房间热度"
                    onChange={(affectsRoomHeat) => updateSection(setForm, "host", { affectsRoomHeat })}
                />
            </div>
        </section>
    );
}

function AgentRuleSection({ disabled, form, setForm }) {
    const agent = form.agent;
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>Agent 规则</h3>
                <Button
                    disabled={disabled}
                    startIcon={<AddOutlined fontSize="small" />}
                    onClick={() => addAgentLevel(setForm)}
                >
                    添加等级
                </Button>
            </div>
            <div className={styles.formGrid}>
                <SelectField
                    disabled={disabled}
                    label="周期"
                    options={agentPeriods}
                    value={agent.period}
                    onChange={(period) => updateSection(setForm, "agent", { period })}
                />
                <NumberField
                    disabled={disabled}
                    label="首月扶持比例"
                    suffix="%"
                    value={agent.supportRatioPercent}
                    onChange={(supportRatioPercent) => updateSection(setForm, "agent", { supportRatioPercent })}
                />
                <NumberField
                    disabled={disabled}
                    label="扶持天数"
                    value={agent.supportDays}
                    onChange={(supportDays) => updateSection(setForm, "agent", { supportDays })}
                />
                <NumberField
                    disabled={disabled}
                    label="合格主播数"
                    value={agent.qualifiedHostMin}
                    onChange={(qualifiedHostMin) => updateSection(setForm, "agent", { qualifiedHostMin })}
                />
                <SwitchField
                    checked={agent.differential.enabled}
                    disabled={disabled}
                    label="跨级差值"
                    onChange={(enabled) => updateAgentDifferential(setForm, { enabled })}
                />
                <NumberField
                    disabled={disabled}
                    label="差值深度"
                    value={agent.differential.maxDepth}
                    onChange={(maxDepth) => updateAgentDifferential(setForm, { maxDepth })}
                />
                <TextField
                    disabled={disabled}
                    label="差值公式"
                    size="small"
                    value={agent.differential.crossLevelFormula}
                    onChange={(event) => updateAgentDifferential(setForm, { crossLevelFormula: event.target.value })}
                />
            </div>
            <div className={styles.levelTable}>
                <div className={styles.agentLevelHeader}>
                    <span>等级</span>
                    <span>名称</span>
                    <span>最小 USD</span>
                    <span>最大 USD</span>
                    <span>比例</span>
                    <span>合格主播</span>
                    <span>人工</span>
                    <span />
                </div>
                {agent.levels.map((level, index) => (
                    <div className={styles.agentLevelRow} key={`${level.level}-${index}`}>
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.level}
                            onChange={(value) => updateAgentLevel(setForm, index, { level: value })}
                        />
                        <TextField
                            disabled={disabled}
                            size="small"
                            value={level.name}
                            onChange={(event) => updateAgentLevel(setForm, index, { name: event.target.value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.minUsd}
                            onChange={(value) => updateAgentLevel(setForm, index, { minUsd: value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.maxUsd}
                            onChange={(value) => updateAgentLevel(setForm, index, { maxUsd: value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            suffix="%"
                            value={level.ratioPercent}
                            onChange={(value) => updateAgentLevel(setForm, index, { ratioPercent: value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.qualifiedHostMin}
                            onChange={(value) => updateAgentLevel(setForm, index, { qualifiedHostMin: value })}
                        />
                        <AdminSwitch
                            checked={level.manualReview}
                            disabled={disabled}
                            label={`Agent 等级 ${index + 1} 人工审核`}
                            onChange={(event) =>
                                updateAgentLevel(setForm, index, { manualReview: event.target.checked })
                            }
                        />
                        <RemoveButton
                            disabled={disabled || agent.levels.length <= 1}
                            label="删除 Agent 等级"
                            onClick={() => removeAgentLevel(setForm, index)}
                        />
                    </div>
                ))}
            </div>
        </section>
    );
}

function BDRuleSection({ disabled, form, setForm }) {
    const bd = form.bd;
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>BD 规则</h3>
                <Button
                    disabled={disabled}
                    startIcon={<AddOutlined fontSize="small" />}
                    onClick={() => addBDLevel(setForm)}
                >
                    添加等级
                </Button>
            </div>
            <div className={styles.formGrid}>
                <SelectField
                    disabled={disabled}
                    label="周期"
                    options={bdPeriods}
                    value={bd.period}
                    onChange={(period) => updateSection(setForm, "bd", { period })}
                />
                <TextField
                    disabled={disabled}
                    label="结算基准"
                    size="small"
                    value={bd.base}
                    onChange={(event) => updateSection(setForm, "bd", { base: event.target.value })}
                />
                <NumberField
                    disabled={disabled}
                    label="合格 Agency 数"
                    value={bd.qualifiedAgencyMin}
                    onChange={(qualifiedAgencyMin) => updateSection(setForm, "bd", { qualifiedAgencyMin })}
                />
                <NumberField
                    disabled={disabled}
                    label="每 Agency 主播数"
                    value={bd.qualifiedHostPerAgencyMin}
                    onChange={(qualifiedHostPerAgencyMin) =>
                        updateSection(setForm, "bd", { qualifiedHostPerAgencyMin })
                    }
                />
            </div>
            <div className={styles.levelTable}>
                <div className={styles.bdLevelHeader}>
                    <span>等级</span>
                    <span>名称</span>
                    <span>门槛 USD</span>
                    <span>固定工资</span>
                    <span>提成</span>
                    <span />
                </div>
                {bd.levels.map((level, index) => (
                    <div className={styles.bdLevelRow} key={`${level.level}-${index}`}>
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.level}
                            onChange={(value) => updateBDLevel(setForm, index, { level: value })}
                        />
                        <TextField
                            disabled={disabled}
                            size="small"
                            value={level.name}
                            onChange={(event) => updateBDLevel(setForm, index, { name: event.target.value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.thresholdUsd}
                            onChange={(value) => updateBDLevel(setForm, index, { thresholdUsd: value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            prefix="$"
                            value={level.salaryUsd}
                            onChange={(value) => updateBDLevel(setForm, index, { salaryUsd: value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            suffix="%"
                            value={level.commissionPercent}
                            onChange={(value) => updateBDLevel(setForm, index, { commissionPercent: value })}
                        />
                        <RemoveButton
                            disabled={disabled || bd.levels.length <= 1}
                            label="删除 BD 等级"
                            onClick={() => removeBDLevel(setForm, index)}
                        />
                    </div>
                ))}
            </div>
        </section>
    );
}

function ManagerRuleSection({ disabled, form, setForm }) {
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>经理规则</h3>
            </div>
            <div className={styles.formGrid}>
                <NumberField
                    disabled={disabled}
                    label="币商充值门槛"
                    prefix="$"
                    value={form.manager.coinSellerRechargeThresholdUsd}
                    onChange={(coinSellerRechargeThresholdUsd) =>
                        updateSection(setForm, "manager", { coinSellerRechargeThresholdUsd })
                    }
                />
                <NumberField
                    disabled={disabled}
                    label="币商充值提成"
                    suffix="%"
                    value={form.manager.coinSellerRechargeCommissionPercent}
                    onChange={(coinSellerRechargeCommissionPercent) =>
                        updateSection(setForm, "manager", { coinSellerRechargeCommissionPercent })
                    }
                />
                <NumberField
                    disabled={disabled}
                    label="主播收益提成"
                    suffix="%"
                    value={form.manager.hostPointCommissionPercent}
                    onChange={(hostPointCommissionPercent) =>
                        updateSection(setForm, "manager", { hostPointCommissionPercent })
                    }
                />
            </div>
        </section>
    );
}

function CoinSellerRuleSection({ disabled, form, setForm }) {
    const coinSeller = form.coinSeller;
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>币商规则</h3>
                <Button
                    disabled={disabled}
                    startIcon={<AddOutlined fontSize="small" />}
                    onClick={() => addCoinSellerLevel(setForm)}
                >
                    添加档位
                </Button>
            </div>
            <div className={styles.formGrid}>
                <SwitchField
                    checked={coinSeller.withdrawOrderEnabled}
                    disabled={disabled}
                    label="提现订单"
                    onChange={(withdrawOrderEnabled) => updateSection(setForm, "coinSeller", { withdrawOrderEnabled })}
                />
                <NumberField
                    disabled={disabled}
                    label="订单超时"
                    suffix="秒"
                    value={coinSeller.orderTimeoutSeconds}
                    onChange={(orderTimeoutSeconds) => updateSection(setForm, "coinSeller", { orderTimeoutSeconds })}
                />
                <NumberField
                    disabled={disabled}
                    label="币商结算"
                    suffix="%"
                    value={coinSeller.sellerPointSettlePercent}
                    onChange={(sellerPointSettlePercent) =>
                        updateSection(setForm, "coinSeller", { sellerPointSettlePercent })
                    }
                />
                <NumberField
                    disabled={disabled}
                    label="币商奖励"
                    suffix="%"
                    value={coinSeller.sellerPointRewardPercent}
                    onChange={(sellerPointRewardPercent) =>
                        updateSection(setForm, "coinSeller", { sellerPointRewardPercent })
                    }
                />
                <NumberField
                    disabled={disabled}
                    label="成功率关闭门槛"
                    suffix="%"
                    value={coinSeller.successRateCloseThresholdPercent}
                    onChange={(successRateCloseThresholdPercent) =>
                        updateSection(setForm, "coinSeller", { successRateCloseThresholdPercent })
                    }
                />
            </div>
            <div className={styles.levelTable}>
                <div className={styles.coinSellerLevelHeader}>
                    <span>名称</span>
                    <span>累计门槛</span>
                    <span>单次门槛</span>
                    <span>金币/USD</span>
                    <span>订单</span>
                    <span />
                </div>
                {coinSeller.levels.map((level, index) => (
                    <div className={styles.coinSellerLevelRow} key={`${level.name}-${index}`}>
                        <TextField
                            disabled={disabled}
                            size="small"
                            value={level.name}
                            onChange={(event) => updateCoinSellerLevel(setForm, index, { name: event.target.value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            prefix="$"
                            value={level.thresholdUsd}
                            onChange={(value) => updateCoinSellerLevel(setForm, index, { thresholdUsd: value })}
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            prefix="$"
                            value={level.singleRechargeThresholdUsd}
                            onChange={(value) =>
                                updateCoinSellerLevel(setForm, index, { singleRechargeThresholdUsd: value })
                            }
                        />
                        <NumberField
                            bare
                            disabled={disabled}
                            value={level.coinPerUsd}
                            onChange={(value) => updateCoinSellerLevel(setForm, index, { coinPerUsd: value })}
                        />
                        <AdminSwitch
                            checked={level.withdrawOrderEnabled}
                            disabled={disabled}
                            label={`币商档位 ${index + 1} 提现订单`}
                            onChange={(event) =>
                                updateCoinSellerLevel(setForm, index, { withdrawOrderEnabled: event.target.checked })
                            }
                        />
                        <RemoveButton
                            disabled={disabled || coinSeller.levels.length <= 1}
                            label="删除币商档位"
                            onClick={() => removeCoinSellerLevel(setForm, index)}
                        />
                    </div>
                ))}
            </div>
        </section>
    );
}

function TaskAndGameRuleSection({ disabled, form, setForm }) {
    return (
        <section className={styles.formSection}>
            <div className={styles.sectionHeader}>
                <h3>任务与游戏邀请</h3>
            </div>
            <div className={styles.formGrid}>
                <SelectField
                    disabled={disabled}
                    label="任务奖励资产"
                    options={taskAssets}
                    value={form.tasks.rewardAssetType}
                    onChange={(rewardAssetType) => updateSection(setForm, "tasks", { rewardAssetType })}
                />
                <NumberField
                    disabled={disabled}
                    label="新主播 7 日任务上限"
                    value={form.tasks.newHost7dMaxPoints}
                    onChange={(newHost7dMaxPoints) => updateSection(setForm, "tasks", { newHost7dMaxPoints })}
                />
                <SwitchField
                    checked={form.gameInvite.enabled}
                    disabled={disabled}
                    label="游戏邀请返利"
                    onChange={(enabled) => updateSection(setForm, "gameInvite", { enabled })}
                />
                <SelectField
                    disabled={disabled}
                    label="游戏邀请周期"
                    options={gameInvitePeriods}
                    value={form.gameInvite.period}
                    onChange={(period) => updateSection(setForm, "gameInvite", { period })}
                />
            </div>
        </section>
    );
}

function NumberField({ bare = false, disabled, label, onChange, prefix, suffix, value }) {
    return (
        <TextField
            disabled={disabled}
            label={bare ? undefined : label}
            size="small"
            slotProps={{
                htmlInput: { min: 0, step: "any" },
                input: {
                    startAdornment: prefix ? <InputAdornment position="start">{prefix}</InputAdornment> : undefined,
                    endAdornment: suffix ? <InputAdornment position="end">{suffix}</InputAdornment> : undefined,
                },
            }}
            type="number"
            value={value}
            onChange={(event) => onChange(event.target.value)}
        />
    );
}

function SelectField({ disabled, label, onChange, options, value }) {
    return (
        <TextField
            select
            disabled={disabled}
            label={label}
            size="small"
            value={value}
            onChange={(event) => onChange(event.target.value)}
        >
            {options.map(([optionValue, optionLabel]) => (
                <MenuItem key={optionValue} value={optionValue}>
                    {optionLabel}
                </MenuItem>
            ))}
        </TextField>
    );
}

function SwitchField({ checked, disabled, label, onChange }) {
    return (
        <div className={styles.switchField}>
            <span>{label}</span>
            <AdminSwitch
                checked={checked}
                checkedLabel="开"
                disabled={disabled}
                label={label}
                uncheckedLabel="关"
                onChange={(event) => onChange(event.target.checked)}
            />
        </div>
    );
}

function RemoveButton({ disabled, label, onClick }) {
    return (
        <IconButton disabled={disabled} label={label} tone="danger" onClick={onClick}>
            <DeleteOutlineOutlined fontSize="small" />
        </IconButton>
    );
}

function updateRule(setForm, patch) {
    setForm((current) => ({ ...current, rule: { ...current.rule, ...patch } }));
}

function updateSection(setForm, section, patch) {
    setForm((current) => ({
        ...current,
        rule: { ...current.rule, [section]: { ...current.rule[section], ...patch } },
    }));
}

function updateAgentDifferential(setForm, patch) {
    setForm((current) => ({
        ...current,
        rule: {
            ...current.rule,
            agent: {
                ...current.rule.agent,
                differential: { ...current.rule.agent.differential, ...patch },
            },
        },
    }));
}

function updateAgentLevel(setForm, index, patch) {
    updateArrayItem(setForm, "agent", "levels", index, patch);
}

function updateBDLevel(setForm, index, patch) {
    updateArrayItem(setForm, "bd", "levels", index, patch);
}

function updateCoinSellerLevel(setForm, index, patch) {
    updateArrayItem(setForm, "coinSeller", "levels", index, patch);
}

function updateArrayItem(setForm, section, key, index, patch) {
    setForm((current) => ({
        ...current,
        rule: {
            ...current.rule,
            [section]: {
                ...current.rule[section],
                [key]: current.rule[section][key].map((item, itemIndex) =>
                    itemIndex === index ? { ...item, ...patch } : item,
                ),
            },
        },
    }));
}

function addAgentLevel(setForm) {
    setForm((current) => {
        const last = current.rule.agent.levels[current.rule.agent.levels.length - 1];
        const nextLevel = Number(last?.level || current.rule.agent.levels.length) + 1;
        return {
            ...current,
            rule: {
                ...current.rule,
                agent: {
                    ...current.rule.agent,
                    levels: [
                        ...current.rule.agent.levels,
                        {
                            level: String(nextLevel),
                            manualReview: false,
                            maxUsd: "0",
                            minUsd: last?.maxUsd || "0",
                            name: `Lv${nextLevel}`,
                            qualifiedHostMin: last?.qualifiedHostMin || "0",
                            ratioPercent: last?.ratioPercent || "0",
                        },
                    ],
                },
            },
        };
    });
}

function addBDLevel(setForm) {
    setForm((current) => {
        const last = current.rule.bd.levels[current.rule.bd.levels.length - 1];
        const nextLevel = Number(last?.level || current.rule.bd.levels.length) + 1;
        return {
            ...current,
            rule: {
                ...current.rule,
                bd: {
                    ...current.rule.bd,
                    levels: [
                        ...current.rule.bd.levels,
                        {
                            commissionPercent: last?.commissionPercent || "0",
                            level: String(nextLevel),
                            name: `BD-${nextLevel}`,
                            salaryUsd: last?.salaryUsd || "0",
                            thresholdUsd: "",
                        },
                    ],
                },
            },
        };
    });
}

function addCoinSellerLevel(setForm) {
    setForm((current) => ({
        ...current,
        rule: {
            ...current.rule,
            coinSeller: {
                ...current.rule.coinSeller,
                levels: [
                    ...current.rule.coinSeller.levels,
                    {
                        coinPerUsd: "0",
                        name: "",
                        singleRechargeThresholdUsd: "",
                        thresholdUsd: "",
                        withdrawOrderEnabled: false,
                    },
                ],
            },
        },
    }));
}

function removeAgentLevel(setForm, index) {
    removeArrayItem(setForm, "agent", "levels", index);
}

function removeBDLevel(setForm, index) {
    removeArrayItem(setForm, "bd", "levels", index);
}

function removeCoinSellerLevel(setForm, index) {
    removeArrayItem(setForm, "coinSeller", "levels", index);
}

function removeArrayItem(setForm, section, key, index) {
    setForm((current) => ({
        ...current,
        rule: {
            ...current.rule,
            [section]: {
                ...current.rule[section],
                [key]: current.rule[section][key].filter((_, itemIndex) => itemIndex !== index),
            },
        },
    }));
}
