import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
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 MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useCallback, useState } from "react";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import { PERMISSIONS } from "@/app/permissions";
import {
    deletePointWithdrawalCoinSeller,
    listPointWithdrawalCoinSellers,
    upsertPointWithdrawalCoinSeller,
} from "@/features/host-org/pointWithdrawalApi";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
} 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 { useToast } from "@/shared/ui/ToastProvider.jsx";
import { formatMillis } from "@/shared/utils/time.js";

const emptyForm = {
    sellerUserId: "",
    sortOrder: "0",
    pointAmount: "",
    sellerCoinAmount: "",
    serviceCountryCodes: "",
    status: "active",
};

export function PointWithdrawalConfigPage() {
    const { appCode } = useAppScope();
    const { can } = useAuth();
    const { showToast } = useToast();
    const canUpdate = can(PERMISSIONS.pointWithdrawalConfigUpdate);
    const [editing, setEditing] = useState(null);
    const [form, setForm] = useState(emptyForm);
    const [saving, setSaving] = useState(false);
    const queryFn = useCallback(() => listPointWithdrawalCoinSellers(), []);
    const query = useAdminQuery(queryFn, {
        errorMessage: "获取币商提现白名单失败",
        queryKey: ["point-withdrawal-coin-sellers", appCode],
    });

    const openCreate = () => {
        setEditing({ mode: "create" });
        setForm(emptyForm);
    };
    const openEdit = (item) => {
        setEditing({ mode: "edit", sellerUserId: item.sellerUserId });
        setForm({
            sellerUserId: item.sellerUserId,
            sortOrder: String(item.sortOrder),
            pointAmount: String(item.pointAmount),
            sellerCoinAmount: String(item.sellerCoinAmount),
            serviceCountryCodes: (item.serviceCountryCodes || []).join(", "),
            status: item.status || "active",
        });
    };
    const closeDialog = () => {
        if (!saving) setEditing(null);
    };

    const submit = async () => {
        const sellerUserId = Number(form.sellerUserId);
        const sortOrder = Number(form.sortOrder);
        const pointAmount = Number(form.pointAmount);
        const sellerCoinAmount = Number(form.sellerCoinAmount);
        if (
            ![sellerUserId, sortOrder, pointAmount, sellerCoinAmount].every(Number.isSafeInteger) ||
            sellerUserId <= 0 ||
            sortOrder < 0 ||
            pointAmount <= 0 ||
            sellerCoinAmount <= 0
        ) {
            showToast("币商 ID、排序和兑换比例必须填写有效整数", "error");
            return;
        }
        setSaving(true);
        try {
            // 国家码只负责展示/准入范围；去重和大写会在 Admin API 再做一次，避免不同客户端写出不同格式。
            const serviceCountryCodes = [
                ...new Set(
                    form.serviceCountryCodes
                        .split(/[,，\s]+/)
                        .map((value) => value.trim().toUpperCase())
                        .filter(Boolean),
                ),
            ];
            await upsertPointWithdrawalCoinSeller({
                sellerUserId,
                sortOrder,
                pointAmount,
                sellerCoinAmount,
                serviceCountryCodes,
                status: form.status,
            });
            showToast("币商提现配置已保存", "success");
            setEditing(null);
            await query.reload();
        } catch (error) {
            showToast(error.message || "保存币商提现配置失败", "error");
        } finally {
            setSaving(false);
        }
    };

    const remove = async (item) => {
        if (!window.confirm(`确认删除币商 ${item.displayUserId || item.sellerUserId} 的提现配置？`)) return;
        try {
            await deletePointWithdrawalCoinSeller(item.sellerUserId);
            showToast("币商提现配置已删除", "success");
            await query.reload();
        } catch (error) {
            showToast(error.message || "删除币商提现配置失败", "error");
        }
    };

    const columns = (() => {
        const base = [
            { key: "sortOrder", label: "排序", render: (item) => item.sortOrder, width: "90px" },
            {
                key: "seller",
                label: "币商",
                render: (item) => <SellerCell item={item} />,
                width: "minmax(220px, 1.2fr)",
            },
            {
                key: "countries",
                label: "服务国家",
                render: (item) => (item.serviceCountryCodes?.length ? item.serviceCountryCodes.join(", ") : "全部国家"),
                width: "minmax(160px, 1fr)",
            },
            {
                key: "ratio",
                label: "主播 POINT : 币商金币",
                render: (item) => `${formatNumber(item.pointAmount)} : ${formatNumber(item.sellerCoinAmount)}`,
                width: "minmax(210px, 1fr)",
            },
            {
                key: "status",
                label: "状态",
                render: (item) => (item.status === "active" ? "启用" : "停用"),
                width: "100px",
            },
            { key: "updatedAtMs", label: "更新时间", render: (item) => formatMillis(item.updatedAtMs), width: "170px" },
        ];
        if (canUpdate) {
            base.push({
                key: "actions",
                label: "操作",
                width: "120px",
                render: (item) => (
                    <AdminRowActions>
                        <AdminActionIconButton label="编辑" onClick={() => openEdit(item)}>
                            <EditOutlined fontSize="small" />
                        </AdminActionIconButton>
                        <AdminActionIconButton label="删除" onClick={() => remove(item)}>
                            <DeleteOutlineOutlined fontSize="small" />
                        </AdminActionIconButton>
                    </AdminRowActions>
                ),
            });
        }
        return base;
    })();

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    canUpdate ? (
                        <Button startIcon={<AddOutlined />} variant="primary" onClick={openCreate}>
                            添加币商
                        </Button>
                    ) : null
                }
                filters={<span>当前 App：{appCode} · 配置为空时 H5 不展示币商提现选项</span>}
            />
            <AdminListBody>
                <DataState error={query.error} loading={query.loading} onRetry={query.reload}>
                    <DataTable
                        columns={columns}
                        items={query.data?.items || []}
                        minWidth="980px"
                        rowKey={(item) => item.sellerUserId}
                    />
                </DataState>
            </AdminListBody>
            <Dialog fullWidth maxWidth="sm" open={Boolean(editing)} onClose={closeDialog}>
                <DialogTitle>{editing?.mode === "edit" ? "编辑币商提现配置" : "添加币商提现配置"}</DialogTitle>
                <DialogContent sx={{ display: "grid", gap: 2, paddingTop: "16px !important" }}>
                    <TextField
                        disabled={editing?.mode === "edit"}
                        label="币商用户 ID"
                        required
                        value={form.sellerUserId}
                        onChange={(event) => setForm({ ...form, sellerUserId: event.target.value })}
                    />
                    <TextField
                        label="排序"
                        required
                        type="number"
                        value={form.sortOrder}
                        onChange={(event) => setForm({ ...form, sortOrder: event.target.value })}
                    />
                    <TextField
                        label="主播 POINT 数量"
                        required
                        type="number"
                        value={form.pointAmount}
                        onChange={(event) => setForm({ ...form, pointAmount: event.target.value })}
                    />
                    <TextField
                        label="币商金币数量"
                        required
                        type="number"
                        value={form.sellerCoinAmount}
                        onChange={(event) => setForm({ ...form, sellerCoinAmount: event.target.value })}
                    />
                    <TextField
                        helperText="使用 ISO 国家码，逗号分隔；留空表示全部国家"
                        label="服务国家"
                        value={form.serviceCountryCodes}
                        onChange={(event) => setForm({ ...form, serviceCountryCodes: event.target.value })}
                    />
                    <TextField
                        select
                        label="状态"
                        value={form.status}
                        onChange={(event) => setForm({ ...form, status: event.target.value })}
                    >
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="disabled">停用</MenuItem>
                    </TextField>
                </DialogContent>
                <DialogActions>
                    <Button disabled={saving} onClick={closeDialog}>
                        取消
                    </Button>
                    <Button disabled={saving} variant="primary" onClick={submit}>
                        保存
                    </Button>
                </DialogActions>
            </Dialog>
        </AdminListPage>
    );
}

function SellerCell({ item }) {
    return (
        <div>
            <strong>{item.nickname || "未找到用户"}</strong>
            <div>
                {item.displayUserId || "-"} · UID {item.sellerUserId}
            </div>
            <small>{item.countryName || "-"}</small>
        </div>
    );
}

function formatNumber(value) {
    return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
