import PlayArrowOutlined from "@mui/icons-material/PlayArrowOutlined";
import DownloadOutlined from "@mui/icons-material/DownloadOutlined";
import ExpandLessOutlined from "@mui/icons-material/ExpandLessOutlined";
import ExpandMoreOutlined from "@mui/icons-material/ExpandMoreOutlined";
import TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";
import { Button } from "@/shared/ui/Button.jsx";
import { FieldLabel } from "@/features/lucky-gift/components/FieldLabel.jsx";
import { runLuckyGiftSimulation } from "@/features/lucky-gift/simulation.js";
import styles from "@/features/lucky-gift/lucky-gift.module.css";

const simulationHelp = {
    costMax: "单次抽奖消耗的最高金币数，用于模拟不同价格幸运礼物混合抽奖。",
    costMin: "单次抽奖消耗的最低金币数，用于模拟低价幸运礼物。",
    drawsMax: "单个用户本次模拟最多抽奖次数。",
    drawsMin: "单个用户本次模拟最少抽奖次数，可以填 0 表示有用户未参与。",
    rooms: "模拟用户随机分散进入的房间数量，用于观察房间维度分布。",
    users: "参与模拟的用户数量，每个用户都会生成独立抽奖次数和 RTP。",
};

const defaultInput = {
    costMax: "500000",
    costMin: "100",
    drawsMax: "100000",
    drawsMin: "0",
    rooms: "50",
    users: "1000",
};

export function LuckyGiftSimulationPanel({ config }) {
    const [expanded, setExpanded] = useState(false);
    const [input, setInput] = useState(defaultInput);
    const [result, setResult] = useState(null);
    const [csvUrl, setCsvUrl] = useState("");

    useEffect(() => {
        return () => {
            if (csvUrl) {
                URL.revokeObjectURL(csvUrl);
            }
        };
    }, [csvUrl]);

    const csvFileName = `lucky-gift-simulation-${new Date().toISOString().slice(0, 10)}.csv`;

    const runSimulation = () => {
        const seed = nextSimulationSeed();
        const nextResult = runLuckyGiftSimulation(config, { ...input, seed });
        const blob = new Blob([`\ufeff${nextResult.csv}`], { type: "text/csv;charset=utf-8" });
        const nextUrl = URL.createObjectURL(blob);
        if (csvUrl) {
            URL.revokeObjectURL(csvUrl);
        }
        setResult(nextResult);
        setCsvUrl(nextUrl);
    };

    return (
        <section className={styles.simulationPanel}>
            <div className={styles.simulationHeader}>
                <div>
                    <span className={styles.title}>随机模拟测试</span>
                </div>
                <div className={styles.simulationActions}>
                    {expanded ? (
                        <>
                            <Button
                                startIcon={<PlayArrowOutlined fontSize="small" />}
                                type="button"
                                variant="primary"
                                onClick={runSimulation}
                            >
                                测试
                            </Button>
                            {csvUrl ? (
                                <Button
                                    component="a"
                                    download={csvFileName}
                                    href={csvUrl}
                                    startIcon={<DownloadOutlined fontSize="small" />}
                                >
                                    CSV
                                </Button>
                            ) : null}
                        </>
                    ) : null}
                    <Button
                        aria-expanded={expanded}
                        endIcon={
                            expanded ? <ExpandLessOutlined fontSize="small" /> : <ExpandMoreOutlined fontSize="small" />
                        }
                        type="button"
                        onClick={() => setExpanded((current) => !current)}
                    >
                        {expanded ? "收起" : "展开"}
                    </Button>
                </div>
            </div>
            {expanded ? (
                <>
                    <div className={styles.simulationGrid}>
                        <NumberField
                            help={simulationHelp.users}
                            label="用户数量"
                            min={1}
                            value={input.users}
                            onChange={(value) => updateInput(setInput, "users", value)}
                        />
                        <NumberField
                            help={simulationHelp.rooms}
                            label="房间数量"
                            min={1}
                            value={input.rooms}
                            onChange={(value) => updateInput(setInput, "rooms", value)}
                        />
                        <NumberField
                            help={simulationHelp.costMin}
                            label="单抽花费最小值"
                            min={1}
                            value={input.costMin}
                            onChange={(value) => updateInput(setInput, "costMin", value)}
                        />
                        <NumberField
                            help={simulationHelp.costMax}
                            label="单抽花费最大值"
                            min={1}
                            value={input.costMax}
                            onChange={(value) => updateInput(setInput, "costMax", value)}
                        />
                        <NumberField
                            help={simulationHelp.drawsMin}
                            label="抽奖次数最小值"
                            min={0}
                            value={input.drawsMin}
                            onChange={(value) => updateInput(setInput, "drawsMin", value)}
                        />
                        <NumberField
                            help={simulationHelp.drawsMax}
                            label="抽奖次数最大值"
                            min={0}
                            value={input.drawsMax}
                            onChange={(value) => updateInput(setInput, "drawsMax", value)}
                        />
                    </div>
                    {result ? <SimulationOverview overview={result.overview} /> : null}
                </>
            ) : null}
        </section>
    );
}

function NumberField({ help, label, min, onChange, value }) {
    return (
        <TextField
            inputProps={{ min, step: 1 }}
            label={<FieldLabel help={help} text={label} />}
            type="number"
            value={value}
            onChange={(event) => onChange(event.target.value)}
        />
    );
}

function SimulationOverview({ overview }) {
    return (
        <div className={styles.simulationOverview}>
            <Metric label="用户" value={formatNumber(overview.users)} />
            <Metric label="房间" value={formatNumber(overview.rooms)} />
            <Metric label="总抽数" value={formatNumber(overview.totalDraws)} />
            <Metric label="平台收入" value={formatNumber(overview.totalSpend)} />
            <Metric label="平台支出" value={formatNumber(overview.totalReward)} />
            <Metric label="总 RTP" value={`${formatRatio(overview.totalRTP)}%`} />
            <Metric label="人均 RTP" value={`${formatRatio(overview.averageUserRTP)}%`} />
            <Metric label="用户净收益" value={formatNumber(overview.totalNetIncome)} />
        </div>
    );
}

function Metric({ label, value }) {
    return (
        <div className={styles.metricItem}>
            <span>{label}</span>
            <strong>{value}</strong>
        </div>
    );
}

function updateInput(setInput, key, value) {
    setInput((current) => ({ ...current, [key]: value }));
}

function nextSimulationSeed() {
    if (globalThis.crypto?.getRandomValues) {
        const values = new Uint32Array(1);
        globalThis.crypto.getRandomValues(values);
        return values[0];
    }
    return Math.round(Date.now() + Math.random() * 0xffffffff);
}

function formatNumber(value) {
    return new Intl.NumberFormat("zh-CN").format(Math.round(Number(value || 0)));
}

function formatRatio(value) {
    return Number(value || 0).toFixed(2);
}
