import SaveOutlined from "@mui/icons-material/SaveOutlined";
import InputAdornment from "@mui/material/InputAdornment";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useCallback, useEffect, useMemo, useState } from "react";
import { getGiftDiamondRatios, updateGiftDiamondRatios } from "@/features/operations/api";
import { useGiftDiamondAbilities } from "@/features/operations/permissions.js";
import styles from "@/features/operations/operations.module.css";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { AdminListPage, AdminListToolbar } from "@/shared/ui/AdminListLayout.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const giftTypes = [
    { label: "普通礼物", value: "normal" },
    { label: "Lucky 礼物", value: "lucky" },
    { label: "Super Lucky 礼物", value: "super_lucky" },
];

const defaultRatios = {
    normal: "100.00",
    lucky: "10.00",
    super_lucky: "1.00",
};

const defaultReturnCoinRatios = {
    normal: "30.00",
    lucky: "10.00",
    super_lucky: "1.00",
};

export function GiftDiamondRatioPage() {
    const abilities = useGiftDiamondAbilities();
    const { showToast } = useToast();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [regionId, setRegionId] = useState("0");
    const [form, setForm] = useState({ ratios: defaultRatios, returnCoinRatios: defaultReturnCoinRatios });
    const [saving, setSaving] = useState(false);

    const queryFn = useCallback(() => getGiftDiamondRatios(regionId), [regionId]);
    const query = useAdminQuery(queryFn, {
        errorMessage: "获取礼物钻石比例失败",
        queryKey: ["gift-diamond-ratios", regionId],
    });

    useEffect(() => {
        const nextRatios = { ...defaultRatios };
        const nextReturnCoinRatios = { ...defaultReturnCoinRatios };
        for (const item of query.data?.items || []) {
            if (Object.prototype.hasOwnProperty.call(nextRatios, item.giftTypeCode)) {
                nextRatios[item.giftTypeCode] = item.ratioPercent || defaultRatios[item.giftTypeCode];
                nextReturnCoinRatios[item.giftTypeCode] =
                    item.returnCoinRatioPercent || defaultReturnCoinRatios[item.giftTypeCode];
            }
        }
        setForm({ ratios: nextRatios, returnCoinRatios: nextReturnCoinRatios });
    }, [query.data]);

    const selectedRegionLabel = useMemo(() => {
        if (regionId === "0") {
            return "全局默认";
        }
        return regionOptions.find((option) => option.value === regionId)?.label || `区域 ${regionId}`;
    }, [regionId, regionOptions]);

    const changeRatio = (field, giftType, value) => {
        setForm((current) => ({ ...current, [field]: { ...current[field], [giftType]: value } }));
    };

    const submit = async () => {
        const ratios = {};
        const returnCoinRatios = {};
        for (const giftType of giftTypes) {
            const value = String(form.ratios[giftType.value] || "").trim();
            const numeric = Number(value);
            if (!value || !Number.isFinite(numeric) || numeric < 0 || numeric > 100) {
                showToast(`${giftType.label}主播钻石比例必须在 0-100 之间`, "error");
                return;
            }
            ratios[giftType.value] = numeric.toFixed(2);
            const returnCoinValue = String(form.returnCoinRatios[giftType.value] || "").trim();
            const returnCoinNumeric = Number(returnCoinValue);
            if (!returnCoinValue || !Number.isFinite(returnCoinNumeric) || returnCoinNumeric < 0 || returnCoinNumeric > 100) {
                showToast(`${giftType.label}返还金币比例必须在 0-100 之间`, "error");
                return;
            }
            returnCoinRatios[giftType.value] = returnCoinNumeric.toFixed(2);
        }
        setSaving(true);
        try {
            const result = await updateGiftDiamondRatios({ regionId: Number(regionId), ratios, returnCoinRatios });
            const nextRatios = { ...defaultRatios };
            const nextReturnCoinRatios = { ...defaultReturnCoinRatios };
            for (const item of result.items || []) {
                if (Object.prototype.hasOwnProperty.call(nextRatios, item.giftTypeCode)) {
                    nextRatios[item.giftTypeCode] = item.ratioPercent || defaultRatios[item.giftTypeCode];
                    nextReturnCoinRatios[item.giftTypeCode] =
                        item.returnCoinRatioPercent || defaultReturnCoinRatios[item.giftTypeCode];
                }
            }
            setForm({ ratios: nextRatios, returnCoinRatios: nextReturnCoinRatios });
            showToast("礼物钻石比例已保存", "success");
            await query.reload();
        } catch (err) {
            showToast(err.message || "保存礼物钻石比例失败", "error");
        } finally {
            setSaving(false);
        }
    };

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    abilities.canUpdate ? (
                        <Button disabled={saving || query.loading} startIcon={<SaveOutlined />} variant="primary" onClick={submit}>
                            保存
                        </Button>
                    ) : null
                }
                filters={
                    <TextField
                        select
                        label="区域"
                        size="small"
                        value={regionId}
                        onChange={(event) => setRegionId(event.target.value)}
                        sx={{ minWidth: 260 }}
                    >
                        <MenuItem value="0">全局默认 · 0</MenuItem>
                        {regionOptions.map((option) => (
                            <MenuItem key={option.value} value={option.value}>
                                {option.label}
                            </MenuItem>
                        ))}
                    </TextField>
                }
            />
            <DataState error={query.error} loading={query.loading || loadingRegions} onRetry={query.reload}>
                <div className={styles.ratioBody}>
                    <section className={styles.ratioPanel}>
                        <div className={styles.ratioHeader}>
                            <h2>{selectedRegionLabel}</h2>
                        </div>
                        <div className={styles.ratioTable}>
                            <div className={styles.ratioTableHeader}>礼物类型</div>
                            <div className={styles.ratioTableHeader}>主播钻石比例</div>
                            <div className={styles.ratioTableHeader}>返还金币比例</div>
                            {giftTypes.map((giftType) => (
                                <div key={giftType.value} className={styles.ratioRow}>
                                    <div className={styles.ratioType}>{giftType.label}</div>
                                    <TextField
                                        label="主播钻石比例"
                                        type="number"
                                        size="small"
                                        value={form.ratios[giftType.value] || ""}
                                        inputProps={{ max: 100, min: 0, step: "0.01" }}
                                        InputProps={{
                                            endAdornment: <InputAdornment position="end">%</InputAdornment>,
                                        }}
                                        disabled={!abilities.canUpdate || saving}
                                        onChange={(event) => changeRatio("ratios", giftType.value, event.target.value)}
                                    />
                                    <TextField
                                        label="返还金币比例"
                                        type="number"
                                        size="small"
                                        value={form.returnCoinRatios[giftType.value] || ""}
                                        inputProps={{ max: 100, min: 0, step: "0.01" }}
                                        InputProps={{
                                            endAdornment: <InputAdornment position="end">%</InputAdornment>,
                                        }}
                                        disabled={!abilities.canUpdate || saving}
                                        onChange={(event) =>
                                            changeRatio("returnCoinRatios", giftType.value, event.target.value)
                                        }
                                    />
                                </div>
                            ))}
                        </div>
                    </section>
                </div>
            </DataState>
        </AdminListPage>
    );
}
