import CampaignOutlined from "@mui/icons-material/CampaignOutlined";
import SendOutlined from "@mui/icons-material/SendOutlined";
import Alert from "@mui/material/Alert";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useMemo, useState } from "react";
import { createFullServerNoticeFanout } from "@/features/operations/api";
import { useFullServerNoticeAbilities } from "@/features/operations/permissions.js";
import styles from "@/features/operations/operations.module.css";
import { AdminListPage, AdminListToolbar } from "@/shared/ui/AdminListLayout.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const messageTypes = [
    { label: "系统消息", value: "system" },
    { label: "活动消息", value: "activity" },
];

const targetScopes = [
    { label: "全量活跃用户", value: "all_active_users" },
    { label: "指定用户", value: "single_user" },
    { label: "用户列表", value: "user_ids" },
    { label: "指定区域", value: "region" },
    { label: "指定国家", value: "country" },
];

const actionTypes = [
    { label: "无跳转", value: "" },
    { label: "活动详情", value: "activity_detail" },
    { label: "H5 页面", value: "app_h5" },
    { label: "房间详情", value: "room_detail" },
    { label: "用户主页", value: "user_profile" },
    { label: "提现详情", value: "wallet_withdraw_detail" },
    { label: "主播申请", value: "host_application_detail" },
    { label: "币商转账", value: "coin_seller_transfer_detail" },
];

const initialForm = {
    actionParam: "",
    actionType: "",
    aggregateId: "",
    aggregateType: "admin_notice",
    batchSize: "500",
    body: "",
    commandId: "",
    country: "",
    expireAt: "",
    messageType: "system",
    metadataJson: "",
    priority: "0",
    producerEventType: "admin_full_server_notice",
    regionId: "",
    summary: "",
    targetScope: "all_active_users",
    targetUserId: "",
    title: "",
    userIds: "",
};

export function FullServerNoticePage() {
    const abilities = useFullServerNoticeAbilities();
    const { showToast } = useToast();
    const [form, setForm] = useState(initialForm);
    const [result, setResult] = useState(null);
    const [saving, setSaving] = useState(false);

    const targetLabel = useMemo(
        () => targetScopes.find((item) => item.value === form.targetScope)?.label || form.targetScope,
        [form.targetScope],
    );

    const updateField = (field) => (event) => {
        setForm((current) => ({ ...current, [field]: event.target.value }));
    };

    const submit = async () => {
        const payload = buildPayload(form);
        if (!payload.ok) {
            showToast(payload.error, "error");
            return;
        }
        setSaving(true);
        try {
            const next = await createFullServerNoticeFanout(payload.value);
            setResult(next);
            showToast(next.created ? "全服通知任务已创建" : "已返回现有通知任务", "success");
        } catch (err) {
            showToast(err.message || "创建全服通知失败", "error");
        } finally {
            setSaving(false);
        }
    };

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    abilities.canSend ? (
                        <Button disabled={saving} startIcon={<SendOutlined />} variant="primary" onClick={submit}>
                            发送
                        </Button>
                    ) : null
                }
                filters={null}
            />
            <div className={styles.noticeBody}>
                <section className={styles.noticePanel}>
                    <div className={styles.noticeHeader}>
                        <CampaignOutlined fontSize="small" />
                        <h2>全服通知</h2>
                    </div>
                    <div className={styles.noticeGrid}>
                        <TextField
                            select
                            label="消息类型"
                            size="small"
                            value={form.messageType}
                            onChange={updateField("messageType")}
                        >
                            {messageTypes.map((item) => (
                                <MenuItem key={item.value} value={item.value}>
                                    {item.label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <TextField
                            select
                            label="发送范围"
                            size="small"
                            value={form.targetScope}
                            onChange={updateField("targetScope")}
                        >
                            {targetScopes.map((item) => (
                                <MenuItem key={item.value} value={item.value}>
                                    {item.label}
                                </MenuItem>
                            ))}
                        </TextField>
                        {form.targetScope === "single_user" ? (
                            <TextField
                                label="用户 ID"
                                size="small"
                                value={form.targetUserId}
                                onChange={updateField("targetUserId")}
                            />
                        ) : null}
                        {form.targetScope === "user_ids" ? (
                            <TextField
                                label="用户 ID 列表"
                                size="small"
                                value={form.userIds}
                                onChange={updateField("userIds")}
                            />
                        ) : null}
                        {form.targetScope === "region" ? (
                            <TextField
                                label="区域 ID"
                                size="small"
                                value={form.regionId}
                                onChange={updateField("regionId")}
                            />
                        ) : null}
                        {form.targetScope === "country" ? (
                            <TextField
                                label="国家"
                                size="small"
                                value={form.country}
                                onChange={updateField("country")}
                            />
                        ) : null}
                        <TextField
                            label="幂等命令 ID"
                            size="small"
                            value={form.commandId}
                            onChange={updateField("commandId")}
                        />
                        <TextField
                            label="批量大小"
                            size="small"
                            type="number"
                            value={form.batchSize}
                            onChange={updateField("batchSize")}
                        />
                    </div>
                    <div className={styles.noticeContentGrid}>
                        <TextField
                            required
                            label="标题"
                            size="small"
                            value={form.title}
                            onChange={updateField("title")}
                        />
                        <TextField
                            required
                            label="摘要"
                            size="small"
                            value={form.summary}
                            onChange={updateField("summary")}
                        />
                        <TextField
                            multiline
                            minRows={4}
                            className={styles.noticeWideField}
                            label="正文"
                            value={form.body}
                            onChange={updateField("body")}
                        />
                    </div>
                    <div className={styles.noticeGrid}>
                        <TextField
                            select
                            label="跳转类型"
                            size="small"
                            value={form.actionType}
                            onChange={updateField("actionType")}
                        >
                            {actionTypes.map((item) => (
                                <MenuItem key={item.value || "none"} value={item.value}>
                                    {item.label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <TextField
                            label="跳转参数"
                            size="small"
                            value={form.actionParam}
                            onChange={updateField("actionParam")}
                        />
                        <TextField
                            label="关联类型"
                            size="small"
                            value={form.aggregateType}
                            onChange={updateField("aggregateType")}
                        />
                        <TextField
                            label="关联 ID"
                            size="small"
                            value={form.aggregateId}
                            onChange={updateField("aggregateId")}
                        />
                        <TextField
                            label="事件类型"
                            size="small"
                            value={form.producerEventType}
                            onChange={updateField("producerEventType")}
                        />
                        <TextField
                            label="优先级"
                            size="small"
                            type="number"
                            value={form.priority}
                            onChange={updateField("priority")}
                        />
                        <TextField
                            label="过期时间"
                            size="small"
                            type="datetime-local"
                            value={form.expireAt}
                            InputLabelProps={{ shrink: true }}
                            onChange={updateField("expireAt")}
                        />
                        <TextField
                            multiline
                            minRows={3}
                            label="Metadata JSON"
                            value={form.metadataJson}
                            onChange={updateField("metadataJson")}
                        />
                    </div>
                </section>
                <section className={styles.noticePreview}>
                    <h3>{form.title || "标题"}</h3>
                    <p>{form.summary || "摘要"}</p>
                    <div className={styles.noticePreviewMeta}>
                        <span>{messageTypes.find((item) => item.value === form.messageType)?.label}</span>
                        <span>{targetLabel}</span>
                        <span>{form.actionType || "无跳转"}</span>
                    </div>
                    {result ? (
                        <Alert severity={result.created ? "success" : "info"}>
                            {result.status} · {result.job_id} · {result.command_id}
                        </Alert>
                    ) : null}
                </section>
            </div>
        </AdminListPage>
    );
}

function buildPayload(form) {
    const title = form.title.trim();
    const summary = form.summary.trim();
    if (!title || !summary) {
        return { error: "标题和摘要不能为空", ok: false };
    }
    const batchSize = parsePositiveNumber(form.batchSize, "批量大小");
    if (!batchSize.ok) {
        return batchSize;
    }
    const priority = parseOptionalNumber(form.priority, "优先级");
    if (!priority.ok) {
        return priority;
    }
    const expireAtMS = datetimeLocalToMS(form.expireAt);
    if (!expireAtMS.ok) {
        return expireAtMS;
    }
    const target = buildTargetPayload(form);
    if (!target.ok) {
        return target;
    }
    const metadataJson = form.metadataJson.trim();
    if (metadataJson) {
        try {
            JSON.parse(metadataJson);
        } catch {
            return { error: "Metadata JSON 不正确", ok: false };
        }
    }
    return {
        ok: true,
        value: {
            ...target.value,
            action_param: form.actionParam.trim() || undefined,
            action_type: form.actionType,
            aggregate_id: form.aggregateId.trim() || undefined,
            aggregate_type: form.aggregateType.trim() || undefined,
            batch_size: batchSize.value,
            body: form.body.trim() || undefined,
            command_id: form.commandId.trim() || undefined,
            expire_at_ms: expireAtMS.value || undefined,
            message_type: form.messageType,
            metadata_json: metadataJson || undefined,
            priority: priority.value,
            producer_event_type: form.producerEventType.trim() || undefined,
            summary,
            target_scope: form.targetScope,
            title,
        },
    };
}

function buildTargetPayload(form) {
    if (form.targetScope === "single_user") {
        const targetUserID = parsePositiveNumber(form.targetUserId, "用户 ID");
        return targetUserID.ok ? { ok: true, value: { target_user_id: targetUserID.value } } : targetUserID;
    }
    if (form.targetScope === "user_ids") {
        const ids = form.userIds
            .split(/[\s,，]+/)
            .map((item) => Number(item.trim()))
            .filter((value) => Number.isInteger(value) && value > 0);
        if (!ids.length) {
            return { error: "用户 ID 列表不能为空", ok: false };
        }
        return { ok: true, value: { user_ids: Array.from(new Set(ids)) } };
    }
    if (form.targetScope === "region") {
        const regionID = parsePositiveNumber(form.regionId, "区域 ID");
        return regionID.ok ? { ok: true, value: { region_id: regionID.value } } : regionID;
    }
    if (form.targetScope === "country") {
        const country = form.country.trim();
        return country ? { ok: true, value: { country } } : { error: "国家不能为空", ok: false };
    }
    return { ok: true, value: {} };
}

function parsePositiveNumber(value, label) {
    const number = Number(String(value || "").trim());
    if (!Number.isInteger(number) || number <= 0) {
        return { error: `${label} 必须是正整数`, ok: false };
    }
    return { ok: true, value: number };
}

function parseOptionalNumber(value, label) {
    const raw = String(value ?? "").trim();
    if (!raw) {
        return { ok: true, value: 0 };
    }
    const number = Number(raw);
    if (!Number.isInteger(number)) {
        return { error: `${label} 必须是整数`, ok: false };
    }
    return { ok: true, value: number };
}

function datetimeLocalToMS(value) {
    if (!value) {
        return { ok: true, value: 0 };
    }
    const ms = new Date(value).getTime();
    if (!Number.isFinite(ms)) {
        return { error: "过期时间不正确", ok: false };
    }
    return { ok: true, value: ms };
}
