import Button from "@mui/material/Button";
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 TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";

export function FinanceCoinSellerGrantDialog({ loading, onClose, onGrant, order }) {
    const [confirmationInput, setConfirmationInput] = useState("");
    const [finalConfirmOpen, setFinalConfirmOpen] = useState(false);
    const confirmationText = buildCoinSellerGrantConfirmationText(order);
    const inputMatches = confirmationInput === confirmationText;

    useEffect(() => {
        // 每次切换订单都必须清空复输内容和二次确认状态，避免上一笔订单的验证结果被复用到新订单。
        setConfirmationInput("");
        setFinalConfirmOpen(false);
    }, [order?.id]);

    const close = () => {
        if (!loading) {
            onClose();
        }
    };

    const openFinalConfirm = () => {
        // 按钮禁用是主要约束，这里仍重复校验，防止脚本触发或状态切换绕过完整文字验证。
        if (inputMatches) {
            setFinalConfirmOpen(true);
        }
    };

    const grant = () => {
        // 接口调用前再次绑定当前订单和完整校验文本，确保只有三重验证流程的最后一步能够发放金币。
        if (order && inputMatches) {
            onGrant(order);
            // 提交后立即关闭，避免接口状态回写前重复点击；失败信息仍由页面现有 toast 统一反馈。
            onClose();
        }
    };

    return (
        <>
            <Dialog fullWidth maxWidth="sm" open={Boolean(order) && !finalConfirmOpen} onClose={close}>
                <DialogTitle>发放金币验证</DialogTitle>
                <DialogContent className="finance-grant-dialog">
                    <strong className="finance-grant-dialog__statement">{confirmationText}</strong>
                    <span className="finance-grant-dialog__warning">请在下方输入框完整填写一遍上面的文字，中间不能有空格</span>
                    <TextField
                        autoComplete="off"
                        autoFocus
                        disabled={loading}
                        error={Boolean(confirmationInput) && !inputMatches}
                        fullWidth
                        label="完整输入发放文字"
                        value={confirmationInput}
                        onChange={(event) => setConfirmationInput(event.target.value)}
                    />
                </DialogContent>
                <DialogActions>
                    <Button disabled={loading} onClick={close}>
                        取消
                    </Button>
                    <Button disabled={loading || !inputMatches} variant="contained" onClick={openFinalConfirm}>
                        确认
                    </Button>
                </DialogActions>
            </Dialog>

            <Dialog fullWidth maxWidth="xs" open={Boolean(order) && finalConfirmOpen} onClose={close}>
                <DialogTitle>确认发放金币</DialogTitle>
                <DialogContent className="finance-grant-dialog finance-grant-dialog--final">
                    <strong>是否确认发放？</strong>
                    <span>{confirmationText}</span>
                </DialogContent>
                <DialogActions>
                    <Button disabled={loading} onClick={() => setFinalConfirmOpen(false)}>
                        返回
                    </Button>
                    <Button disabled={loading} variant="contained" onClick={grant}>
                        {loading ? "发放中" : "确认发放"}
                    </Button>
                </DialogActions>
            </Dialog>
        </>
    );
}

export function buildCoinSellerGrantConfirmationText(order) {
    const usdAmount = plainNumber(order?.usdAmount ?? Number(order?.usdMinorAmount || 0) / 100);
    const userId = order?.targetDisplayUserId || order?.targetUserId || "-";
    const coinAmount = plainNumber(order?.coinAmount);
    return `本订单金额${usdAmount}USDT将会向用户${userId}的币商账户发放${coinAmount}金币`;
}

function plainNumber(value) {
    const number = Number(value);
    return Number.isFinite(number) ? String(number) : "-";
}
