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 { createSystemMessagePushFanout } from "@/features/app-config/api";
import { useSystemMessagePushAbilities } from "@/features/app-config/permissions.js";
import { parseSystemMessagePushUserIds, systemMessagePushSchema } from "@/features/app-config/schema";
import styles from "@/features/app-config/app-config.module.css";
import { FormValidationError, parseForm } from "@/shared/forms/validation";
import { AdminListPage, AdminListToolbar } from "@/shared/ui/AdminListLayout.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { useConfirm } from "@/shared/ui/ConfirmProvider.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const targetScopes = [
    { label: "所有注册用户", value: "all_registered_users" },
    { label: "指定用户", value: "user_ids" },
];

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: "",
    body: "",
    summary: "",
    targetScope: "all_registered_users",
    title: "",
    userIdsText: "",
};

export function SystemMessagePushPage() {
    const abilities = useSystemMessagePushAbilities();
    const confirm = useConfirm();
    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 () => {
        let parsed;
        try {
            parsed = parseForm(systemMessagePushSchema, form);
        } catch (error) {
            if (error instanceof FormValidationError) {
                showToast(error.message, "error");
                return;
            }
            throw error;
        }

        const userIds = parsed.targetScope === "user_ids" ? parseSystemMessagePushUserIds(parsed.userIdsText) : [];
        const targetText =
            parsed.targetScope === "all_registered_users" ? "所有注册用户" : `${userIds.length} 个指定用户`;
        const accepted = await confirm({
            confirmText: "发送",
            message: `将向${targetText}发送「${parsed.title}」。`,
            title: "发送系统消息",
        });
        if (!accepted) {
            return;
        }

        setSaving(true);
        try {
            const next = await createSystemMessagePushFanout(buildPayload(parsed, userIds));
            setResult(next);
            showToast(next.created ? "系统消息推送任务已创建" : "已返回现有系统消息推送任务", "success");
        } catch (error) {
            showToast(error.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 label="消息类型" size="small" value="系统消息" disabled />
                        <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 === "user_ids" ? (
                            <TextField
                                className={styles.noticeWideField}
                                label="用户 ID 列表"
                                minRows={3}
                                multiline
                                placeholder="1001,1002"
                                value={form.userIdsText}
                                onChange={updateField("userIdsText")}
                            />
                        ) : null}
                    </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
                            className={styles.noticeWideField}
                            label="正文"
                            minRows={4}
                            multiline
                            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")}
                        />
                    </div>
                </section>
                <section className={styles.noticePreview}>
                    <h3>{form.title || "标题"}</h3>
                    <p>{form.summary || "摘要"}</p>
                    <div className={styles.noticePreviewMeta}>
                        <span>系统消息</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, userIds) {
    return {
        action_param: form.actionParam || undefined,
        action_type: form.actionType || undefined,
        aggregate_type: "admin_notice",
        batch_size: 500,
        body: form.body || undefined,
        message_type: "system",
        producer_event_type: "admin_full_server_notice",
        summary: form.summary,
        target_scope: form.targetScope,
        title: form.title,
        user_ids: form.targetScope === "user_ids" ? userIds : undefined,
    };
}
