import ExpandMoreOutlined from "@mui/icons-material/ExpandMoreOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import QueryStatsOutlined from "@mui/icons-material/QueryStatsOutlined";
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 FormControlLabel from "@mui/material/FormControlLabel";
import InputAdornment from "@mui/material/InputAdornment";
import Switch from "@mui/material/Switch";
import TextField from "@mui/material/TextField";
import { useMemo, useState } from "react";
import { WheelPrizeTable } from "@/features/operations/components/WheelPrizeTable.jsx";
import { useWheelPage } from "@/features/operations/hooks/useWheelPage.js";
import { useWheelAbilities } from "@/features/operations/permissions.js";
import styles from "@/features/operations/operations.module.css";
import { AdminListBody, AdminListPage } from "@/shared/ui/AdminListLayout.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";

const drawStatusOptions = [
    ["", "全部状态"],
    ["pending", "待发放"],
    ["granted", "已发放"],
    ["failed", "发放失败"],
];

const drawColumns = [
    {
        key: "drawId",
        label: "抽奖 ID",
        width: "minmax(200px, 1fr)",
        render: (draw) => draw.drawId || "-",
    },
    {
        key: "reward",
        label: "奖品",
        width: "minmax(180px, 0.9fr)",
        render: (draw) => (
            <div className={styles.wheelRewardCell}>
                <strong>{rewardTypeLabel(draw.rewardType)}</strong>
                <span>{rewardValue(draw)}</span>
            </div>
        ),
    },
    {
        key: "rtp",
        label: "RTP价值",
        width: "minmax(120px, 0.65fr)",
        render: (draw) => formatNumber(draw.rtpValueCoins),
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(120px, 0.65fr)",
        render: (draw) => drawStatusLabel(draw.rewardStatus),
    },
    {
        key: "actualRtp",
        label: "窗口 RTP",
        width: "minmax(120px, 0.65fr)",
        render: (draw) => ppmToPercent(draw.actualRTPPPM),
    },
    {
        key: "createdAtMs",
        label: "时间",
        width: "minmax(170px, 0.85fr)",
        render: (draw) => <TimeText value={draw.createdAtMs} />,
    },
];

export function WheelPage() {
    const abilities = useWheelAbilities();
    const state = useWheelPage();
    const draws = state.draws || { items: [], total: 0, page: state.page, pageSize: state.pageSize };
    const summary = useMemo(() => state.summary || {}, [state.summary]);
    const disableForm = state.saving || state.configQuery.loading;
    const [statsOpen, setStatsOpen] = useState(false);
    const [configOpen, setConfigOpen] = useState(false);

    const summaryItems = useMemo(
        () => [
            ["总抽数", formatNumber(summary.totalDraws)],
            ["参与用户", formatNumber(summary.uniqueUsers)],
            ["消耗金币", formatNumber(summary.totalSpentCoins)],
            ["RTP奖值", formatNumber(summary.totalRTPValueCoins)],
            ["实际 RTP", ppmToPercent(summary.actualRTPPPM)],
            ["已发放", formatNumber(summary.grantedDraws)],
            ["待发放", formatNumber(summary.pendingDraws)],
            ["失败", formatNumber(summary.failedDraws)],
        ],
        [summary],
    );

    return (
        <AdminListPage>
            <div className={styles.wheelTopBar}>
                <div className={styles.wheelPoolTabs}>
                    {state.wheelPools.map((pool) => (
                        <button
                            className={[styles.wheelPoolTab, state.wheelId === pool.key ? styles.wheelPoolTabActive : ""]
                                .filter(Boolean)
                                .join(" ")}
                            key={pool.key}
                            type="button"
                            onClick={() => state.selectPool(pool.key)}
                        >
                            <span>{pool.label}</span>
                            <strong>{pool.tierCount} 档</strong>
                        </button>
                    ))}
                </div>
                <div className={styles.wheelActionBar}>
                    <Button startIcon={<QueryStatsOutlined />} onClick={() => setStatsOpen(true)}>
                        抽奖统计
                    </Button>
                    <Button
                        disabled={state.configQuery.loading || state.drawQuery.loading}
                        startIcon={<RefreshOutlined />}
                        onClick={() => {
                            state.configQuery.reload();
                            state.summaryQuery.reload();
                            state.drawQuery.reload();
                        }}
                    >
                        刷新
                    </Button>
                    {abilities.canUpdate ? (
                        <Button
                            disabled={state.saving || state.configQuery.loading}
                            startIcon={<SaveOutlined />}
                            variant="primary"
                            onClick={state.submit}
                        >
                            保存
                        </Button>
                    ) : null}
                </div>
            </div>
            <DataState error={state.configError} loading={state.configQuery.loading} onRetry={state.configQuery.reload}>
                <div className={styles.wheelBody}>
                    <section className={styles.wheelConfigColumn}>
                        <section className={styles.wheelPanel}>
                            <div className={styles.wheelPanelHeader}>
                                <h2>基础配置</h2>
                                <div className={styles.wheelPanelActions}>
                                    <FormControlLabel
                                        control={
                                            <Switch
                                                checked={Boolean(state.form.enabled)}
                                                disabled={!abilities.canUpdate || disableForm}
                                                onChange={(event) => state.changeFormField("enabled", event.target.checked)}
                                            />
                                        }
                                        label={state.form.enabled ? "已启用" : "已关闭"}
                                    />
                                    <button
                                        className={styles.wheelCollapseButton}
                                        type="button"
                                        onClick={() => setConfigOpen((value) => !value)}
                                    >
                                        <ExpandMoreOutlined
                                            className={[
                                                styles.wheelCollapseIcon,
                                                configOpen ? styles.wheelCollapseIconOpen : "",
                                            ]
                                                .filter(Boolean)
                                                .join(" ")}
                                        />
                                        {configOpen ? "收起" : "展开"}
                                    </button>
                                </div>
                            </div>
                            {configOpen ? (
                                <div className={styles.wheelConfigGrid}>
                                    <TextField
                                        label="转盘 ID"
                                        size="small"
                                        value={state.form.wheelId}
                                        disabled
                                    />
                                    <NumberField
                                        label="单抽价格"
                                        value={state.form.drawPriceCoins}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("drawPriceCoins", value)}
                                    />
                                    <PercentField
                                        label="目标 RTP"
                                        value={state.form.targetRTPPercent}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("targetRTPPercent", value)}
                                    />
                                    <PercentField
                                        label="入池比例"
                                        value={state.form.poolRatePercent}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("poolRatePercent", value)}
                                    />
                                    <NumberField
                                        label="结算窗口抽数"
                                        value={state.form.settlementWindowDraws}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("settlementWindowDraws", value)}
                                    />
                                    <NumberField
                                        label="初始奖池"
                                        value={state.form.initialPoolCoins}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("initialPoolCoins", value)}
                                    />
                                    <NumberField
                                        label="奖池保底"
                                        value={state.form.poolReserveCoins}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("poolReserveCoins", value)}
                                    />
                                    <NumberField
                                        label="单次 RTP 上限"
                                        value={state.form.maxSingleRTPPayout}
                                        disabled={!abilities.canUpdate || disableForm}
                                        onChange={(value) => state.changeFormField("maxSingleRTPPayout", value)}
                                    />
                                </div>
                            ) : null}
                        </section>

                        <WheelPrizeTable
                            canUpdate={abilities.canUpdate}
                            disabled={disableForm}
                            expectedCount={state.expectedTierCount}
                            resourceGroupPicker={
                                <ResourceGroupSelectField
                                    disabled={!abilities.canUpdate || disableForm || state.resourceGroupQuery.loading}
                                    drawerTitle="添加奖池"
                                    groups={state.resourceGroups}
                                    label="添加奖池"
                                    placeholder="选择资源组"
                                    value=""
                                    onChange={(_, group) => state.importResourceGroup(group)}
                                />
                            }
                            tiers={state.form.tiers}
                            onChange={state.changeTierField}
                            onMove={state.moveTier}
                        />
                    </section>
                </div>
            </DataState>

            <Dialog
                className={styles.wheelStatsDialog}
                fullWidth
                maxWidth="lg"
                open={statsOpen}
                onClose={() => setStatsOpen(false)}
            >
                <DialogTitle>抽奖统计</DialogTitle>
                <DialogContent>
                    <div className={styles.wheelSummaryGrid}>
                        {summaryItems.map(([label, value]) => (
                            <div className={styles.wheelSummaryItem} key={label}>
                                <span>{label}</span>
                                <strong>{value}</strong>
                            </div>
                        ))}
                    </div>
                    <div className={styles.wheelStatsTable}>
                        <h3>中奖记录</h3>
                        <DataState error={state.drawError} loading={state.drawQuery.loading} onRetry={state.drawQuery.reload}>
                            <AdminListBody>
                                <DataTable
                                    columns={drawColumns}
                                    items={draws.items || []}
                                    minWidth="920px"
                                    pagination={
                                        draws.total > 0
                                            ? {
                                                  page: state.page,
                                                  pageSize: draws.pageSize || state.pageSize,
                                                  total: draws.total,
                                                  onPageChange: state.setPage,
                                              }
                                            : undefined
                                    }
                                    rowKey={(draw) => draw.drawId || `${draw.commandId}-${draw.createdAtMs}`}
                                />
                            </AdminListBody>
                        </DataState>
                    </div>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setStatsOpen(false)}>关闭</Button>
                </DialogActions>
            </Dialog>
        </AdminListPage>
    );
}

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

function PercentField({ disabled, label, onChange, value }) {
    return (
        <TextField
            label={label}
            type="number"
            size="small"
            value={value}
            inputProps={{ min: 0, max: 100, step: "0.01" }}
            InputProps={{ endAdornment: <InputAdornment position="end">%</InputAdornment> }}
            disabled={disabled}
            onChange={(event) => onChange(event.target.value)}
        />
    );
}

function rewardTypeLabel(value) {
    if (value === "coin") {
        return "金币";
    }
    if (value === "gift") {
        return "礼物";
    }
    if (value === "dress") {
        return "装扮";
    }
    if (value === "prop") {
        return "道具";
    }
    return value || "-";
}

function rewardValue(draw) {
    if (draw.rewardType === "coin") {
        return `${formatNumber(draw.rewardCoins)} 金币`;
    }
    const count = draw.rewardCount ? ` x${draw.rewardCount}` : "";
    return `${draw.rewardId || "-"}${count}`;
}

function drawStatusLabel(value) {
    return drawStatusOptions.find(([status]) => status === value)?.[1] || value || "-";
}

function ppmToPercent(value) {
    const ppm = Number(value || 0);
    return `${(ppm / 10000).toFixed(2)}%`;
}

function formatNumber(value) {
    const number = Number(value || 0);
    return Number.isFinite(number) ? number.toLocaleString("en-US") : "0";
}
