import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlined from "@mui/icons-material/DeleteOutlined";
import Checkbox from "@mui/material/Checkbox";
import IconButton from "@mui/material/IconButton";
import TextField from "@mui/material/TextField";
import { Button } from "@/shared/ui/Button.jsx";
import { formatDecimal } from "@/shared/utils/rtpProbability.js";
import { formatNumber } from "../format.js";
import { LuckyGiftFieldLabel } from "./LuckyGiftFieldHelp.jsx";
import { OpsStatusBadge } from "./OpsStatusBadge.jsx";

export function LuckyGiftStageDesigner({
    activeStageConfig,
    activeStageKey,
    activeSummary,
    normalStageConfig,
    onAddTier,
    onRemoveTier,
    onStageChange,
    onStageFieldChange,
    onTierChange,
    stageSummaries,
    strategyVersion,
}) {
    const selectStageFromKeyboard = (event, currentIndex) => {
        const lastIndex = stageSummaries.length - 1;
        let nextIndex;
        if (["ArrowRight", "ArrowDown"].includes(event.key)) nextIndex = (currentIndex + 1) % stageSummaries.length;
        if (["ArrowLeft", "ArrowUp"].includes(event.key))
            nextIndex = (currentIndex - 1 + stageSummaries.length) % stageSummaries.length;
        if (event.key === "Home") nextIndex = 0;
        if (event.key === "End") nextIndex = lastIndex;
        if (nextIndex === undefined) return;
        event.preventDefault();
        const nextStage = stageSummaries[nextIndex]?.stageKey;
        if (!nextStage) return;
        // Tabs 遵循 roving tabindex：方向键既切换阶段，也把焦点移到新 tab，键盘操作不会落回隐藏面板。
        onStageChange(nextStage);
        event.currentTarget.ownerDocument.getElementById(`ops-stage-tab-${nextStage}`)?.focus();
    };

    return (
        <section className="ops-stage-designer" aria-label="普通奖档设计">
            <div className="ops-stage-tabs" role="tablist" aria-label="普通奖档阶段">
                {stageSummaries.map((summary, index) => {
                    const isActive = summary.stageKey === activeStageKey;
                    return (
                        <button
                            aria-controls={`ops-stage-panel-${summary.stageKey}`}
                            aria-selected={isActive}
                            className={`ops-stage-tab ${isActive ? "is-active" : ""} ${summary.ok ? "is-ok" : "is-warn"}`}
                            id={`ops-stage-tab-${summary.stageKey}`}
                            key={summary.stageKey}
                            role="tab"
                            tabIndex={isActive ? 0 : -1}
                            type="button"
                            onClick={() => onStageChange(summary.stageKey)}
                            onKeyDown={(event) => selectStageFromKeyboard(event, index)}
                        >
                            <span className="ops-stage-tab__name">
                                <strong>{summary.tabLabel}</strong>
                                <small>{plainStageStatus(summary.status)}</small>
                            </span>
                            <span className="ops-stage-tab__metrics">
                                概率 {formatDecimal(summary.probability)}% · 平均返还 {formatDecimal(summary.expected)}%
                            </span>
                        </button>
                    );
                })}
            </div>

            {activeStageConfig ? (
                <div
                    aria-labelledby={`ops-stage-tab-${activeStageKey}`}
                    className="ops-stage-stack"
                    id={`ops-stage-panel-${activeStageKey}`}
                    role="tabpanel"
                >
                    <div className="ops-stage-block__head">
                        <div className="ops-stage-block__summary">
                            <h3>
                                <LuckyGiftFieldLabel
                                    field={`stage_${activeStageKey}`}
                                    label={activeSummary?.stageLabel || activeStageKey}
                                />
                            </h3>
                            <OpsStatusBadge
                                label={`${plainStageStatus(activeSummary?.status)} · 概率 ${formatDecimal(activeSummary?.probability)}% · 预计平均返还 ${formatDecimal(activeSummary?.expected)}%`}
                                tone={activeSummary?.ok ? "succeeded" : "warning"}
                            />
                        </div>
                        <Button
                            aria-label={`为${activeSummary?.stageLabel || "当前阶段"}添加奖档`}
                            startIcon={<AddOutlined fontSize="small" />}
                            onClick={() => onAddTier(activeStageConfig.stage)}
                        >
                            添加奖档
                        </Button>
                    </div>

                    {strategyVersion === "dynamic_v3" && activeStageConfig.stage === "novice" ? (
                        <NoviceRechargeRange normalStageConfig={normalStageConfig} />
                    ) : strategyVersion === "dynamic_v3" ? (
                        <div className="ops-stage-thresholds" aria-label={`${activeSummary?.stageLabel}充值门槛`}>
                            <span>进入本阶段所需充值</span>
                            <TextField
                                label={
                                    <LuckyGiftFieldLabel field="min_recharge_7d_coins" label="7 日最低充值（金币）" />
                                }
                                size="small"
                                slotProps={{ htmlInput: { min: 0, step: 1 } }}
                                type="number"
                                value={activeStageConfig.min_recharge_7d_coins}
                                onChange={(event) =>
                                    onStageFieldChange(
                                        activeStageConfig.stage,
                                        "min_recharge_7d_coins",
                                        event.target.value,
                                    )
                                }
                            />
                            <TextField
                                label={
                                    <LuckyGiftFieldLabel field="min_recharge_30d_coins" label="30 日最低充值（金币）" />
                                }
                                size="small"
                                slotProps={{ htmlInput: { min: 0, step: 1 } }}
                                type="number"
                                value={activeStageConfig.min_recharge_30d_coins}
                                onChange={(event) =>
                                    onStageFieldChange(
                                        activeStageConfig.stage,
                                        "min_recharge_30d_coins",
                                        event.target.value,
                                    )
                                }
                            />
                        </div>
                    ) : null}

                    <div className="ops-tier-table" role="table" aria-label={`${activeSummary?.stageLabel}奖档`}>
                        <div className="ops-tier-head" role="row">
                            <span role="columnheader">
                                <LuckyGiftFieldLabel field="tier_multiplier" label="倍率" />
                            </span>
                            <span role="columnheader">
                                <LuckyGiftFieldLabel field="tier_probability" label="普通中奖机会 %" />
                            </span>
                            <span role="columnheader">
                                <LuckyGiftFieldLabel field="tier_high_water_only" label="高倍率安全标记" />
                            </span>
                            <span role="columnheader">
                                <LuckyGiftFieldLabel field="tier_enabled" label="启用" />
                            </span>
                            <span role="columnheader">操作</span>
                        </div>
                        {activeStageConfig.tiers.map((tier, index) => {
                            const rowLabel = `${activeSummary?.stageLabel || activeStageConfig.stage}第 ${index + 1} 档`;
                            return (
                                <div className="ops-tier-row" key={`${activeStageConfig.stage}-${index}`} role="row">
                                    <div className="ops-tier-cell" role="cell">
                                        <TextField
                                            required
                                            size="small"
                                            slotProps={{
                                                htmlInput: {
                                                    "aria-label": `${rowLabel}倍率`,
                                                    inputMode: "decimal",
                                                    min: 0,
                                                    step: "0.01",
                                                },
                                            }}
                                            type="number"
                                            value={tier.multiplier}
                                            onChange={(event) =>
                                                onTierChange(activeStageConfig.stage, index, {
                                                    // 10 倍及以上是服务端发布校验要求的高倍率标记；运行时仍会独立检查真实奖池余额，
                                                    // 不能把前端勾选本身当成资金足够或必然可发奖的依据。
                                                    highWaterOnly:
                                                        Number(event.target.value) >= 10 || tier.highWaterOnly,
                                                    multiplier: event.target.value,
                                                })
                                            }
                                        />
                                    </div>
                                    <div className="ops-tier-cell" role="cell">
                                        {/* 概率由目标 RTP 和倍率统一校正；保持只读可避免运营绕过服务端概率闭合校验。 */}
                                        <TextField
                                            size="small"
                                            slotProps={{
                                                htmlInput: {
                                                    "aria-label": `${rowLabel}概率 %`,
                                                    readOnly: true,
                                                },
                                            }}
                                            value={formatDecimal(tier.probabilityPercent)}
                                        />
                                    </div>
                                    <div className="ops-tier-cell ops-tier-cell--center" role="cell">
                                        <Checkbox
                                            checked={Boolean(tier.highWaterOnly)}
                                            disabled={Number(tier.multiplier) >= 10}
                                            size="small"
                                            slotProps={{ input: { "aria-label": `${rowLabel}高倍率安全标记` } }}
                                            onChange={(event) =>
                                                onTierChange(activeStageConfig.stage, index, {
                                                    highWaterOnly: event.target.checked,
                                                })
                                            }
                                        />
                                    </div>
                                    <div className="ops-tier-cell ops-tier-cell--center" role="cell">
                                        <Checkbox
                                            checked={tier.enabled !== false}
                                            size="small"
                                            slotProps={{ input: { "aria-label": `${rowLabel}启用` } }}
                                            onChange={(event) =>
                                                onTierChange(activeStageConfig.stage, index, {
                                                    enabled: event.target.checked,
                                                })
                                            }
                                        />
                                    </div>
                                    <div className="ops-tier-cell ops-tier-cell--center" role="cell">
                                        <IconButton
                                            aria-label={`删除${rowLabel}`}
                                            color="error"
                                            disabled={activeStageConfig.tiers.length <= 1}
                                            size="small"
                                            title={`删除${rowLabel}`}
                                            onClick={() => onRemoveTier(activeStageConfig.stage, index)}
                                        >
                                            <DeleteOutlined fontSize="small" />
                                        </IconButton>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            ) : null}
        </section>
    );
}

function NoviceRechargeRange({ normalStageConfig }) {
    const normal7D = Number(normalStageConfig?.min_recharge_7d_coins || 0);
    const normal30D = Number(normalStageConfig?.min_recharge_30d_coins || 0);
    // normal 是二维 AND 下限，合法配置只需至少一维大于 0；为 0 的维度也必须照实展示。
    const configured = Number.isFinite(normal7D) && Number.isFinite(normal30D) && (normal7D > 0 || normal30D > 0);

    return (
        <div className="ops-stage-thresholds ops-stage-thresholds--derived" aria-label="新手阶段派生充值范围">
            <span>派生范围</span>
            <div className="ops-stage-threshold-rule">
                <strong>
                    7 日充值 &lt; {formatNumber(normal7D)} 或 30 日充值 &lt; {formatNumber(normal30D)}
                </strong>
                {/* 普通阶段需要两个下限同时成立；因此任一维未达到都应留在新手，等于下限则进入普通。 */}
                <small>
                    {configured ? "" : "普通阶段门槛待配置；"}任一未达到即为新手；7 日与 30
                    日均达到门槛（含等于）后进入普通。
                </small>
            </div>
        </div>
    );
}

function plainStageStatus(status) {
    if (status === "RTP 偏离") return "平均返还偏离";
    if (status === "概率未闭合") return "概率合计不为 100%";
    return status || "待检查";
}
