import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import SettingsOutlined from "@mui/icons-material/SettingsOutlined";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useCallback, useEffect, useMemo, useState } from "react";
import { PERMISSIONS } from "@/app/permissions";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import { getRoomRpsConfig, updateRoomRpsConfig } from "@/features/games/api";
import { listGifts } from "@/features/resources/api";
import { GiftPreviewSelectField } from "@/features/resources/components/GiftSelectDrawer.jsx";
import styles from "@/features/games/games.module.css";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
} from "@/shared/ui/AdminListLayout.jsx";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormSection,
    AdminFormSwitchField,
} from "@/shared/ui/AdminFormDialog.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { PageSkeleton } from "@/shared/ui/PageSkeleton.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { formatMillis } from "@/shared/utils/time.js";

const defaultStakeGifts = [1, 2, 3, 4].map((sortOrder) => ({
    enabled: true,
    giftId: "",
    sortOrder,
}));

const defaultForm = {
    status: "active",
    challengeTimeoutMs: 600000,
    revealCountdownMs: 3000,
    stakeGifts: defaultStakeGifts,
};

export function RoomRpsConfigPage() {
    const { can } = useAuth();
    const { showToast } = useToast();
    const canUpdate = can(PERMISSIONS.gameUpdate);
    const [config, setConfig] = useState(null);
    const [form, setForm] = useState(defaultForm);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [editing, setEditing] = useState(false);
    const [gifts, setGifts] = useState([]);
    const [giftsLoading, setGiftsLoading] = useState(true);

    const load = useCallback(async () => {
        setLoading(true);
        try {
            const result = await getRoomRpsConfig();
            setConfig(result.config);
        } catch (err) {
            showToast(err.message || "加载房内猜拳配置失败", "error");
        } finally {
            setLoading(false);
        }
    }, [showToast]);

    const loadGifts = useCallback(async () => {
        setGiftsLoading(true);
        try {
            const result = await listGifts({ page_size: 200, status: "active" });
            setGifts(result.items || []);
        } catch (err) {
            showToast(err.message || "加载礼物列表失败", "error");
        } finally {
            setGiftsLoading(false);
        }
    }, [showToast]);

    useEffect(() => {
        load();
        loadGifts();
    }, [load, loadGifts]);

    const refresh = useCallback(() => {
        load();
        loadGifts();
    }, [load, loadGifts]);

    const rows = useMemo(() => (config ? [config] : []), [config]);
    const columns = useMemo(
        () => [
            {
                key: "game",
                label: "玩法",
                width: "minmax(180px, 1fr)",
                render: (item) => (
                    <div className={styles.identityText}>
                        <span className={styles.name}>房内猜拳</span>
                        <span className={styles.meta}>{item.gameId || "room_rps"}</span>
                    </div>
                ),
            },
            {
                key: "status",
                label: "状态",
                width: "120px",
                render: (item) => statusText(item.status),
            },
            {
                key: "timeout",
                label: "时长",
                width: "minmax(180px, 1fr)",
                render: (item) =>
                    `${formatSeconds(item.challengeTimeoutMs)} / ${formatSeconds(item.revealCountdownMs)}`,
            },
            {
                key: "gifts",
                label: "礼物档位",
                width: "minmax(260px, 1.5fr)",
                render: (item) =>
                    (item.stakeGifts || [])
                        .map(
                            (gift) =>
                                `${gift.sortOrder}:${gift.giftName || gift.giftId}${gift.enabled ? "" : "(停用)"}`,
                        )
                        .join(" / "),
            },
            {
                key: "updated",
                label: "更新时间",
                width: "minmax(170px, 1fr)",
                render: (item) => (item.updatedAtMs ? formatMillis(item.updatedAtMs) : "-"),
            },
            {
                key: "actions",
                label: "操作",
                width: "88px",
                render: (item) => (
                    <AdminRowActions>
                        <AdminActionIconButton disabled={!canUpdate} label="编辑" onClick={() => openEditor(item)}>
                            <SettingsOutlined fontSize="small" />
                        </AdminActionIconButton>
                    </AdminRowActions>
                ),
            },
        ],
        [canUpdate],
    );

    const openEditor = (item) => {
        setForm(configToForm(item));
        setEditing(true);
    };

    const submit = async (event) => {
        event.preventDefault();
        const validationError = validateStakeGifts(form.stakeGifts);
        if (validationError) {
            showToast(validationError, "error");
            return;
        }
        const payload = formToPayload(form);
        setSaving(true);
        try {
            const result = await updateRoomRpsConfig(payload);
            setConfig(result.config);
            setEditing(false);
            showToast("房内猜拳配置已保存", "success");
        } catch (err) {
            showToast(err.message || "保存房内猜拳配置失败", "error");
        } finally {
            setSaving(false);
        }
    };

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

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <AdminActionIconButton label="刷新" onClick={refresh}>
                        <RefreshOutlined fontSize="small" />
                    </AdminActionIconButton>
                }
            />
            <AdminListBody>
                <DataTable
                    columns={columns}
                    items={rows}
                    minWidth="980px"
                    rowKey={(item) => item.gameId || "room_rps"}
                />
            </AdminListBody>
            <RoomRpsConfigDialog
                form={form}
                gifts={gifts}
                giftsLoading={giftsLoading}
                loading={saving}
                open={editing}
                setForm={setForm}
                onClose={() => setEditing(false)}
                onSubmit={submit}
            />
        </AdminListPage>
    );
}

function RoomRpsConfigDialog({ form, gifts, giftsLoading, loading, open, setForm, onClose, onSubmit }) {
    return (
        <AdminFormDialog
            loading={loading}
            open={open}
            submitLabel="保存配置"
            title="房内猜拳配置"
            size="large"
            onClose={onClose}
            onSubmit={onSubmit}
        >
            <AdminFormSection title="基础">
                <AdminFormFieldGrid>
                    <TextField
                        label="状态"
                        select
                        value={form.status}
                        onChange={(event) => setForm({ ...form, status: event.target.value })}
                    >
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="disabled">停用</MenuItem>
                    </TextField>
                    <TextField
                        label="挑战超时 ms"
                        type="number"
                        value={form.challengeTimeoutMs}
                        onChange={(event) => setForm({ ...form, challengeTimeoutMs: event.target.value })}
                    />
                    <TextField
                        label="揭晓倒计时 ms"
                        type="number"
                        value={form.revealCountdownMs}
                        onChange={(event) => setForm({ ...form, revealCountdownMs: event.target.value })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="礼物档位">
                <div className={styles.giftTierList}>
                    {form.stakeGifts.map((gift, index) => (
                        <div className={styles.giftTierRow} key={gift.sortOrder || index}>
                            <GiftPreviewSelectField
                                badge={`${Number(gift.sortOrder || index + 1)} 档`}
                                className={styles.giftTierGift}
                                drawerTitle={`选择第 ${index + 1} 档礼物`}
                                fallbackGift={gift}
                                gifts={gifts}
                                label={`第 ${index + 1} 档礼物`}
                                loading={giftsLoading}
                                placeholder="点击选择礼物"
                                value={gift.giftId}
                                onChange={(value, selectedGift) =>
                                    setGiftTier(setForm, form, index, giftPatchFromSelected(value, selectedGift))
                                }
                            />
                            <div className={styles.giftTierControls}>
                                <TextField
                                    className={styles.giftTierSort}
                                    label="排序"
                                    size="small"
                                    type="number"
                                    value={gift.sortOrder}
                                    onChange={(event) =>
                                        setGiftTier(setForm, form, index, { sortOrder: event.target.value })
                                    }
                                />
                                <AdminFormSwitchField
                                    checked={gift.enabled}
                                    checkedLabel="启用"
                                    className={styles.giftTierSwitch}
                                    label={`第 ${index + 1} 档启用状态`}
                                    uncheckedLabel="停用"
                                    onChange={(checked) => setGiftTier(setForm, form, index, { enabled: checked })}
                                />
                            </div>
                        </div>
                    ))}
                </div>
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function setGiftTier(setForm, form, index, patch) {
    const stakeGifts = form.stakeGifts.map((gift, giftIndex) => (giftIndex === index ? { ...gift, ...patch } : gift));
    setForm({ ...form, stakeGifts });
}

function configToForm(config) {
    const stakeGifts = [...(config.stakeGifts || [])]
        .sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0))
        .slice(0, 4)
        .map((gift, index) => ({
            enabled: gift.enabled !== false,
            giftId: gift.giftId || "",
            giftIconUrl: gift.giftIconUrl || "",
            giftName: gift.giftName || "",
            giftPriceCoin: Number(gift.giftPriceCoin || 0),
            sortOrder: gift.sortOrder || index + 1,
        }));
    while (stakeGifts.length < 4) {
        stakeGifts.push({ ...defaultStakeGifts[stakeGifts.length] });
    }
    return {
        status: config.status || "active",
        challengeTimeoutMs: config.challengeTimeoutMs || 600000,
        revealCountdownMs: config.revealCountdownMs || 3000,
        stakeGifts,
    };
}

function giftPatchFromSelected(giftId, gift) {
    return {
        giftId: String(giftId || "").trim(),
        giftIconUrl: gift?.giftIconUrl || gift?.resource?.previewUrl || gift?.resource?.assetUrl || "",
        giftName: gift?.name || gift?.giftName || gift?.resource?.name || "",
        giftPriceCoin: Number(gift?.coinPrice ?? gift?.giftPriceCoin ?? gift?.resource?.coinPrice ?? 0),
    };
}

function validateStakeGifts(stakeGifts) {
    if (!Array.isArray(stakeGifts) || stakeGifts.length !== 4) {
        return "房内猜拳必须配置 4 个礼物档位";
    }
    const seen = new Set();
    for (let index = 0; index < stakeGifts.length; index += 1) {
        const gift = stakeGifts[index];
        const giftId = String(gift?.giftId || "").trim();
        if (!giftId) {
            return `第 ${index + 1} 档礼物未选择`;
        }
        if (seen.has(giftId)) {
            return `第 ${index + 1} 档礼物重复，请选择不同礼物`;
        }
        seen.add(giftId);
    }
    return "";
}

function formToPayload(form) {
    return {
        status: form.status || "active",
        challengeTimeoutMs: Number(form.challengeTimeoutMs || 600000),
        revealCountdownMs: Number(form.revealCountdownMs || 3000),
        stakeGifts: form.stakeGifts.map((gift, index) => ({
            enabled: gift.enabled !== false,
            giftId: String(gift.giftId || "").trim(),
            sortOrder: Number(gift.sortOrder || index + 1),
        })),
    };
}

function statusText(status) {
    return status === "disabled" ? "停用" : "启用";
}

function formatSeconds(ms) {
    const value = Number(ms || 0);
    if (!value) return "-";
    return `${Math.round(value / 1000)}s`;
}
