import KeyboardArrowDownOutlined from "@mui/icons-material/KeyboardArrowDownOutlined";
import KeyboardArrowRightOutlined from "@mui/icons-material/KeyboardArrowRightOutlined";
import PublicOutlined from "@mui/icons-material/PublicOutlined";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";
import { formatNumber, formatPercentFromPPM } from "../format.js";
import { OpsStatusBadge } from "./OpsStatusBadge.jsx";

export function buildUserProfileColumns(expandedKey) {
    return [
        {
            fixed: "left",
            key: "identity",
            label: "用户身份",
            render: (profile) => <UserIdentityCell expanded={expandedKey === profile.key} profile={profile} />,
            width: "270px",
        },
        windowColumn("one_hour", "近 1 小时", (profile) => profile.windows.oneHour),
        windowColumn("twenty_four_hours", "近 24 小时", (profile) => profile.windows.twentyFourHours),
        windowColumn("forty_eight_hours", "近 48 小时", (profile) => profile.windows.fortyEightHours),
        windowColumn("lifetime", "累计", (profile) => profile.windows.lifetime),
        {
            key: "control_state",
            label: "最近开奖阶段 / 连续未中",
            render: (profile) => <ControlStateCell profile={profile} />,
            width: "190px",
        },
        {
            key: "downweight",
            label: "24 小时 RTP 降权",
            render: (profile) => <DownweightCell profile={profile} />,
            width: "190px",
        },
        {
            key: "ordinary_wins",
            label: "普通中奖",
            render: (profile) => (
                <div className="ops-profile-counts">
                    <strong>{formatNumber(profile.ordinaryWinCount)} 次</strong>
                    <span>其中高倍率 {formatNumber(profile.highMultiplierOrdinaryWinCount)} 次</span>
                    <span>未中奖 {formatNumber(profile.zeroDrawCount)} 次</span>
                    <small>普通奖与大奖通道独立统计</small>
                </div>
            ),
            width: "170px",
        },
        {
            key: "jackpots",
            label: "两类大奖",
            render: (profile) => (
                <div className="ops-profile-counts">
                    <strong>
                        {formatNumber(profile.rtpCompensationJackpotCount + profile.cumulativeSpendJackpotCount)} 次
                    </strong>
                    <span>RTP 补偿 {formatNumber(profile.rtpCompensationJackpotCount)}</span>
                    <span>累计消费 {formatNumber(profile.cumulativeSpendJackpotCount)}</span>
                    <small>点击行查看每次命中依据</small>
                </div>
            ),
            width: "180px",
        },
        {
            key: "last_draw_at_ms",
            label: "最近抽奖",
            render: (profile) => (
                <div className="ops-profile-time">
                    <TimeText value={profile.lastDrawAtMs} />
                    <small>
                        v{profile.latestRuleVersion || "-"} · {profile.latestStrategyVersion || "-"}
                    </small>
                </div>
            ),
            width: "180px",
        },
        {
            key: "data_lag_ms",
            label: "画像时效",
            render: (profile) => (
                <div className="ops-profile-time">
                    <strong>{formatDuration(profile.dataLagMs)}</strong>
                    <small>
                        {profile.failedDrawCount > 0
                            ? `失败 ${formatNumber(profile.failedDrawCount)} 抽`
                            : `已发 ${formatNumber(profile.grantedDrawCount)} · 待处理 ${formatNumber(profile.pendingDrawCount)}`}
                    </small>
                </div>
            ),
            width: "150px",
        },
    ];
}

function windowColumn(key, label, selectMetric) {
    return {
        key,
        label,
        render: (profile) => <WindowMetricCell metric={selectMetric(profile)} />,
        width: "205px",
    };
}

function WindowMetricCell({ metric }) {
    return (
        <div className="ops-profile-window">
            <div className="ops-profile-window__head">
                <strong>{metric.hasRtp ? formatObservedRTP(metric.rtpPpm) : "-"}</strong>
                <small>{formatNumber(metric.drawCount)} 抽</small>
            </div>
            <dl>
                <div>
                    <dt>消耗</dt>
                    <dd>{formatNumber(metric.wagerCoins)}</dd>
                </div>
                <div>
                    <dt>返奖</dt>
                    <dd>{formatNumber(metric.payoutCoins)}</dd>
                </div>
                <div className={metric.netCoins > 0 ? "is-profit" : metric.netCoins < 0 ? "is-loss" : ""}>
                    <dt>用户净输赢</dt>
                    <dd>{formatSignedNumber(metric.netCoins)}</dd>
                </div>
            </dl>
        </div>
    );
}

function UserIdentityCell({ expanded, profile }) {
    return (
        <div className="ops-profile-identity">
            <span className="ops-profile-expand" aria-hidden="true">
                {expanded ? (
                    <KeyboardArrowDownOutlined fontSize="small" />
                ) : (
                    <KeyboardArrowRightOutlined fontSize="small" />
                )}
            </span>
            {profile.identityType === "external" ? (
                <div className="ops-profile-external">
                    <span className="ops-profile-external__icon">
                        <PublicOutlined fontSize="small" />
                    </span>
                    <span>
                        <strong>{profile.externalUserId || "-"}</strong>
                        <small>external_user_id</small>
                    </span>
                </div>
            ) : (
                <div className="ops-profile-internal">
                    <AdminUserIdentity rows={internalIdentityRows(profile.user)} user={profile.user} />
                    <small>内部用户{profile.user.status ? ` · ${userStatusLabel(profile.user.status)}` : ""}</small>
                </div>
            )}
        </div>
    );
}

function ControlStateCell({ profile }) {
    const remaining = profile.guaranteeDrawsRemaining;
    return (
        <div className="ops-profile-control">
            <div>
                <OpsStatusBadge label={stageLabel(profile.stage)} tone={stageTone(profile.stage)} />
                <span>等价抽数 {formatNumber(profile.equivalentDraws)}</span>
            </div>
            <strong>连续未中 {formatNumber(profile.lossStreak)} 次</strong>
            <small>{remaining > 0 ? `距连续未中保护 ${formatNumber(remaining)} 抽` : "连续未中保护剩余 0 抽"}</small>
            {profile.pendingCumulativeSpendTokens > 0 ? (
                <small className="is-warning">
                    待兑累计消费大奖 {formatNumber(profile.pendingCumulativeSpendTokens)} 次
                </small>
            ) : null}
        </div>
    );
}

function DownweightCell({ profile }) {
    const threshold = profile.user24hRtpThresholdPpm;
    const factor = profile.user24hOrdinaryWinFactorPpm;
    return (
        <div className="ops-profile-downweight">
            {profile.downweightActive ? (
                <OpsStatusBadge label={`已降权 · 保留 ${formatPercentFromPPM(factor)}`} tone="warning" />
            ) : (
                <OpsStatusBadge label="未触发" tone="succeeded" />
            )}
            <span>
                当前{" "}
                {profile.hasCurrentRtp || profile.windows.twentyFourHours.hasRtp
                    ? formatObservedRTP(
                          profile.hasCurrentRtp ? profile.currentRtpPpm : profile.windows.twentyFourHours.rtpPpm,
                      )
                    : "暂无消耗"}
            </span>
            <small>
                {threshold > 0
                    ? `严格高于 ${formatPercentFromPPM(threshold)} 时保留 ${formatPercentFromPPM(factor)}`
                    : profile.downweightActive
                      ? `普通中奖机会当前按 ${formatPercentFromPPM(factor)} 发放`
                      : "当前普通中奖机会未被降权"}
            </small>
        </div>
    );
}

function internalIdentityRows(user) {
    const shortID = user.defaultDisplayUserId || user.displayUserId;
    return [shortID ? `短号 ${shortID}` : "", user.userId ? `长号 ${user.userId}` : ""].filter(Boolean);
}

function userStatusLabel(status) {
    const normalized = String(status || "").toLowerCase();
    const labels = {
        active: "正常",
        banned: "已封禁",
        disabled: "已停用",
        inactive: "未激活",
    };
    return labels[normalized] || status;
}

function stageLabel(stage) {
    const normalized = String(stage || "").toLowerCase();
    if (normalized === "novice" || normalized === "newbie" || normalized === "new") {
        return "新手阶段";
    }
    if (normalized === "normal" || normalized === "ordinary") {
        return "普通阶段";
    }
    if (["advanced", "high", "high_value", "premium"].includes(normalized)) {
        return "高价阶段";
    }
    return stage || "阶段未记录";
}

function stageTone(stage) {
    return stage ? "succeeded" : "";
}

function formatSignedNumber(value) {
    const number = Number(value);
    if (!Number.isFinite(number)) {
        return "-";
    }
    return `${number > 0 ? "+" : ""}${formatNumber(number)}`;
}

// 已有消耗时 0 ppm 是真实的 0% 返奖率，不是“暂无数据”；配置字段仍沿用通用格式化器的空值语义。
function formatObservedRTP(value) {
    const number = Number(value);
    if (!Number.isFinite(number) || number < 0) {
        return "-";
    }
    return `${(number / 10_000).toFixed(2)}%`;
}

function formatDuration(value) {
    const milliseconds = Math.max(0, Number(value) || 0);
    if (milliseconds < 1_000) {
        return "实时";
    }
    if (milliseconds < 60_000) {
        return `${Math.floor(milliseconds / 1_000)} 秒`;
    }
    if (milliseconds < 3_600_000) {
        return `${Math.floor(milliseconds / 60_000)} 分钟`;
    }
    return `${(milliseconds / 3_600_000).toFixed(1)} 小时`;
}
