import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import Radio from "@mui/material/Radio";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";
import { formatPercent } from "../format.js";
import { OpsStatusBadge } from "./OpsStatusBadge.jsx";

export function LuckyGiftRollbackDialog({
    config,
    error,
    loading,
    onClose,
    onRetry,
    onSubmit,
    submitting,
    versions,
}) {
    const candidates = useMemo(
        () =>
            (Array.isArray(versions) ? versions : []).filter(
                (item) => Number(item.rule_version) > 0 && Number(item.rule_version) < Number(config.rule_version),
            ),
        [config.rule_version, versions],
    );
    const [selectedVersion, setSelectedVersion] = useState(0);

    useEffect(() => {
        // 历史接口按版本倒序返回，默认选择上一版能减少误操作跨度；若刷新后该版本不存在则重新收敛。
        setSelectedVersion((current) =>
            candidates.some((item) => Number(item.rule_version) === current)
                ? current
                : Number(candidates[0]?.rule_version || 0),
        );
    }, [candidates]);

    return (
        <Dialog
            fullWidth
            maxWidth="lg"
            open
            aria-labelledby="lucky-gift-rollback-title"
            onClose={submitting ? undefined : onClose}
        >
            <DialogTitle id="lucky-gift-rollback-title">
                回滚幸运礼物版本
                <small>
                    {config.app_code} / {config.pool_id} / 当前 v{config.rule_version}
                </small>
            </DialogTitle>
            <DialogContent dividers className="ops-rollback-content">
                <div className="ops-rollback-warning" role="note">
                    回滚会复制所选历史快照并发布为一个新版本，历史版本不会被修改。V2 与 V3 的奖池水位保持独立，切换策略不会搬移、清空或重新注资。
                </div>
                <DataState error={error} loading={loading} onRetry={onRetry} reportPageLoading={false}>
                    {candidates.length ? (
                        <div className="ops-rollback-table" role="radiogroup" aria-label="可回滚版本">
                            <div className="ops-rollback-row ops-rollback-head" aria-hidden="true">
                                <span />
                                <span>版本</span>
                                <span>策略</span>
                                <span>状态</span>
                                <span>目标 RTP</span>
                                <span>进入奖池</span>
                                <span>平台 / 主播</span>
                                <span>发布时间</span>
                            </div>
                            {candidates.map((item) => {
                                const version = Number(item.rule_version);
                                const selected = selectedVersion === version;
                                return (
                                    <label className={selected ? "ops-rollback-row is-selected" : "ops-rollback-row"} key={version}>
                                        <Radio
                                            checked={selected}
                                            disabled={submitting}
                                            inputProps={{ "aria-label": `选择版本 v${version}` }}
                                            size="small"
                                            value={version}
                                            onChange={() => setSelectedVersion(version)}
                                        />
                                        <strong>v{version}</strong>
                                        <span>{item.strategy_version || "fixed_v2"}</span>
                                        <span>
                                            {item.enabled ? (
                                                <OpsStatusBadge label="已启用" tone="succeeded" />
                                            ) : (
                                                <OpsStatusBadge label="已停用" />
                                            )}
                                        </span>
                                        <span>{formatPercent(item.target_rtp_percent)}</span>
                                        <span>{formatPercent(item.pool_rate_percent)}</span>
                                        <span>
                                            {formatPercent(item.profit_rate_percent)} / {formatPercent(item.anchor_rate_percent)}
                                        </span>
                                        <TimeText value={item.created_at_ms} />
                                    </label>
                                );
                            })}
                        </div>
                    ) : (
                        <div className="ops-rollback-empty">当前奖池还没有可回滚的历史版本。</div>
                    )}
                </DataState>
            </DialogContent>
            <DialogActions>
                <Button disabled={submitting} onClick={onClose}>
                    取消
                </Button>
                <Button
                    disabled={submitting || loading || Boolean(error) || selectedVersion <= 0}
                    variant="danger"
                    onClick={() => onSubmit(selectedVersion)}
                >
                    {selectedVersion > 0 ? `确认回滚到 v${selectedVersion}` : "确认回滚"}
                </Button>
            </DialogActions>
        </Dialog>
    );
}
