import BlockOutlined from "@mui/icons-material/BlockOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import ReplayOutlined from "@mui/icons-material/ReplayOutlined";
import VisibilityOutlined from "@mui/icons-material/VisibilityOutlined";
import TextField from "@mui/material/TextField";
import { useCallback, useEffect, useState } from "react";
import { PERMISSIONS } from "@/app/permissions";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import {
    expireRoomRpsChallenge,
    getRoomRpsChallenge,
    listRoomRpsChallenges,
    retryRoomRpsSettlement,
} from "@/features/games/api";
import styles from "@/features/games/games.module.css";
import {
    AdminActionIconButton,
    AdminFilterResetButton,
    AdminFilterSelect,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
} from "@/shared/ui/AdminListLayout.jsx";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormReadOnlyField,
    AdminFormSection,
} from "@/shared/ui/AdminFormDialog.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { PageSkeleton } from "@/shared/ui/PageSkeleton.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { formatMillis } from "@/shared/utils/time.js";

const statusOptions = [
    ["", "全部状态"],
    ["pending", "待应战"],
    ["matched", "已应战"],
    ["revealing", "揭晓中"],
    ["finished", "已完成"],
    ["timeout", "已超时"],
    ["settlement_failed", "结算失败"],
    ["cancelled", "已取消"],
];

const emptyFilters = {
    challengerUserId: "",
    initiatorUserId: "",
    roomId: "",
    status: "",
};

export function RoomRpsChallengePage() {
    const { can } = useAuth();
    const { showToast } = useToast();
    const canUpdate = can(PERMISSIONS.gameUpdate);
    const [items, setItems] = useState([]);
    const [filters, setFilters] = useState(emptyFilters);
    const [timeRange, setTimeRange] = useState({ endMs: "", startMs: "" });
    const [cursor, setCursor] = useState("");
    const [nextCursor, setNextCursor] = useState("");
    const [loading, setLoading] = useState(true);
    const [actionLoading, setActionLoading] = useState("");
    const [detail, setDetail] = useState(null);
    const [detailOpen, setDetailOpen] = useState(false);

    const load = useCallback(
        async (nextCursorValue = "") => {
            setLoading(true);
            try {
                const result = await listRoomRpsChallenges({
                    challengerUserId: filters.challengerUserId || undefined,
                    cursor: nextCursorValue,
                    endTimeMs: timeRange.endMs || undefined,
                    initiatorUserId: filters.initiatorUserId || undefined,
                    pageSize: 50,
                    roomId: filters.roomId || undefined,
                    startTimeMs: timeRange.startMs || undefined,
                    status: filters.status || undefined,
                });
                setItems(result.items || []);
                setCursor(nextCursorValue);
                setNextCursor(result.nextCursor || "");
            } catch (err) {
                showToast(err.message || "加载房内猜拳订单失败", "error");
            } finally {
                setLoading(false);
            }
        },
        [filters, showToast, timeRange],
    );

    useEffect(() => {
        load("");
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    const columns = [
        {
            key: "challenge",
            label: "挑战单",
            width: "minmax(220px, 1.3fr)",
            render: (item) => (
                <div className={styles.identityText}>
                    <span className={styles.name}>{item.challengeId}</span>
                    <span className={styles.meta}>{item.roomId || "-"}</span>
                </div>
            ),
        },
        {
            key: "status",
            label: "状态",
            width: "120px",
            render: (item) => statusText(item.status),
        },
        {
            key: "stake",
            label: "下注",
            width: "minmax(150px, .9fr)",
            render: (item) => `${item.stakeGiftId || "-"} / ${formatNumber(item.stakeCoin)}`,
        },
        {
            key: "users",
            label: "双方",
            width: "minmax(220px, 1.2fr)",
            render: (item) => `${playerText(item.initiator)} / ${playerText(item.challenger)}`,
        },
        {
            key: "settlement",
            label: "结算",
            width: "minmax(160px, .9fr)",
            render: (item) => item.settlementStatus || "-",
        },
        {
            key: "created",
            label: "创建时间",
            width: "minmax(170px, 1fr)",
            render: (item) => (item.createdAtMs ? formatMillis(item.createdAtMs) : "-"),
        },
        {
            key: "actions",
            label: "操作",
            width: "132px",
            render: (item) => (
                <AdminRowActions>
                    <AdminActionIconButton label="详情" onClick={() => openDetail(item.challengeId)}>
                        <VisibilityOutlined fontSize="small" />
                    </AdminActionIconButton>
                    <AdminActionIconButton
                        disabled={
                            !canUpdate || item.status !== "settlement_failed" || actionLoading === item.challengeId
                        }
                        label="重试结算"
                        onClick={() => retrySettlement(item.challengeId)}
                    >
                        <ReplayOutlined fontSize="small" />
                    </AdminActionIconButton>
                    <AdminActionIconButton
                        disabled={!canUpdate || item.status !== "pending" || actionLoading === item.challengeId}
                        label="手动过期"
                        onClick={() => expireChallenge(item.challengeId)}
                    >
                        <BlockOutlined fontSize="small" />
                    </AdminActionIconButton>
                </AdminRowActions>
            ),
        },
    ];

    const updateFilter = (patch) => setFilters((current) => ({ ...current, ...patch }));
    const resetFilters = () => {
        setFilters(emptyFilters);
        setTimeRange({ endMs: "", startMs: "" });
    };

    const openDetail = async (challengeId) => {
        setActionLoading(challengeId);
        try {
            const result = await getRoomRpsChallenge(challengeId);
            setDetail(result.challenge);
            setDetailOpen(true);
        } catch (err) {
            showToast(err.message || "获取房内猜拳订单详情失败", "error");
        } finally {
            setActionLoading("");
        }
    };

    const retrySettlement = async (challengeId) => {
        setActionLoading(challengeId);
        try {
            const result = await retryRoomRpsSettlement(challengeId);
            patchChallenge(result.challenge);
            showToast("结算重试已提交", "success");
        } catch (err) {
            showToast(err.message || "重试结算失败", "error");
        } finally {
            setActionLoading("");
        }
    };

    const expireChallenge = async (challengeId) => {
        setActionLoading(challengeId);
        try {
            const result = await expireRoomRpsChallenge(challengeId);
            patchChallenge(result.challenge);
            showToast("挑战单已过期", "success");
        } catch (err) {
            showToast(err.message || "手动过期失败", "error");
        } finally {
            setActionLoading("");
        }
    };

    const patchChallenge = (challenge) => {
        setItems((current) => current.map((item) => (item.challengeId === challenge.challengeId ? challenge : item)));
        if (detail?.challengeId === challenge.challengeId) {
            setDetail(challenge);
        }
    };

    if (loading) {
        return <PageSkeleton />;
    }

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <>
                        <AdminActionIconButton label="查询" onClick={() => load("")}>
                            <RefreshOutlined fontSize="small" />
                        </AdminActionIconButton>
                        <AdminFilterResetButton onClick={resetFilters} />
                    </>
                }
                filters={
                    <>
                        <TextField
                            label="房间 ID"
                            size="small"
                            value={filters.roomId}
                            onChange={(event) => updateFilter({ roomId: event.target.value })}
                        />
                        <AdminFilterSelect
                            options={statusOptions}
                            value={filters.status}
                            onChange={(value) => updateFilter({ status: value })}
                        />
                        <TextField
                            label="发起人"
                            size="small"
                            value={filters.initiatorUserId}
                            onChange={(event) => updateFilter({ initiatorUserId: event.target.value })}
                        />
                        <TextField
                            label="应战人"
                            size="small"
                            value={filters.challengerUserId}
                            onChange={(event) => updateFilter({ challengerUserId: event.target.value })}
                        />
                        <TimeRangeFilter value={timeRange} onChange={setTimeRange} />
                    </>
                }
            />
            <AdminListBody>
                <DataTable columns={columns} items={items} minWidth="1120px" rowKey={(item) => item.challengeId} />
            </AdminListBody>
            <AdminListToolbar
                actions={
                    nextCursor || cursor ? (
                        <>
                            <AdminActionIconButton disabled={!cursor} label="上一页" onClick={() => load("")}>
                                <ReplayOutlined fontSize="small" />
                            </AdminActionIconButton>
                            <AdminActionIconButton
                                disabled={!nextCursor}
                                label="下一页"
                                onClick={() => load(nextCursor)}
                            >
                                <RefreshOutlined fontSize="small" />
                            </AdminActionIconButton>
                        </>
                    ) : null
                }
            />
            <RoomRpsChallengeDetail challenge={detail} open={detailOpen} onClose={() => setDetailOpen(false)} />
        </AdminListPage>
    );
}

function RoomRpsChallengeDetail({ challenge, open, onClose }) {
    const closeBySubmit = (event) => {
        event.preventDefault();
        onClose();
    };

    return (
        <AdminFormDialog
            open={open}
            submitLabel="关闭"
            title="房内猜拳订单详情"
            onClose={onClose}
            onSubmit={closeBySubmit}
        >
            <AdminFormSection title="订单">
                <AdminFormFieldGrid>
                    <AdminFormReadOnlyField label="挑战单 ID" value={challenge?.challengeId} />
                    <AdminFormReadOnlyField label="房间 ID" value={challenge?.roomId} />
                    <AdminFormReadOnlyField label="状态" value={statusText(challenge?.status)} />
                    <AdminFormReadOnlyField label="结算状态" value={challenge?.settlementStatus} />
                    <AdminFormReadOnlyField label="失败原因" value={challenge?.failureReason} />
                    <AdminFormReadOnlyField label="胜者" value={challenge?.winnerUserId} />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="玩家">
                <AdminFormFieldGrid>
                    <AdminFormReadOnlyField label="发起人" value={detailPlayerText(challenge?.initiator)} />
                    <AdminFormReadOnlyField label="应战人" value={detailPlayerText(challenge?.challenger)} />
                    <AdminFormReadOnlyField label="礼物 ID" value={challenge?.stakeGiftId} />
                    <AdminFormReadOnlyField label="金币" value={formatNumber(challenge?.stakeCoin)} />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="时间">
                <AdminFormFieldGrid>
                    <AdminFormReadOnlyField label="创建" value={timeText(challenge?.createdAtMs)} />
                    <AdminFormReadOnlyField label="超时" value={timeText(challenge?.timeoutAtMs)} />
                    <AdminFormReadOnlyField label="揭晓" value={timeText(challenge?.revealAtMs)} />
                    <AdminFormReadOnlyField label="结算" value={timeText(challenge?.settledAtMs)} />
                </AdminFormFieldGrid>
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function playerText(player) {
    if (!player?.userId) return "-";
    return `${player.userId}:${player.gesture || "-"}`;
}

function detailPlayerText(player) {
    if (!player?.userId) return "-";
    return `${player.userId} / ${player.gesture || "-"} / ${player.result || "-"}`;
}

function statusText(status) {
    return Object.fromEntries(statusOptions)[status] || status || "-";
}

function timeText(ms) {
    return ms ? formatMillis(ms) : "-";
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString("en-US");
}
