import AddOutlined from "@mui/icons-material/AddOutlined";
import CheckCircleOutlineOutlined from "@mui/icons-material/CheckCircleOutlineOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import VisibilityOutlined from "@mui/icons-material/VisibilityOutlined";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import Drawer from "@mui/material/Drawer";
import MenuItem from "@mui/material/MenuItem";
import Snackbar from "@mui/material/Snackbar";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useEffect, useState } from "react";
import {
    approveAgencyOpeningApplication,
    createAgencyOpeningCycle,
    listAgencyOpeningApplications,
    listAgencyOpeningCycles,
    setAgencyOpeningCycleStatus,
    updateAgencyOpeningCycle,
} from "@/features/agency-opening/api";
import { useAgencyOpeningAbilities } from "@/features/agency-opening/permissions.js";
import { Button } from "@/shared/ui/Button.jsx";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
} from "@/shared/ui/AdminListLayout.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";

const statusOptions = [
    ["draft", "草稿"],
    ["active", "启用"],
    ["disabled", "停用"],
    ["settling", "结算中"],
    ["settled", "已结算"],
];

const emptyForm = {
    cycleId: "",
    title: "代理开业活动",
    status: "draft",
    startMs: "",
    endMs: "",
    minHostCount: "10",
    maxAgencyAgeDays: "30",
    rewards: [
        { rankNo: 1, thresholdCoinSpent: "500000", rewardCoinAmount: "50000" },
        { rankNo: 2, thresholdCoinSpent: "1000000", rewardCoinAmount: "100000" },
        { rankNo: 3, thresholdCoinSpent: "3000000", rewardCoinAmount: "300000" },
        { rankNo: 4, thresholdCoinSpent: "5000000", rewardCoinAmount: "500000" },
        { rankNo: 5, thresholdCoinSpent: "10000000", rewardCoinAmount: "500000" },
    ],
};

export function AgencyOpeningPage() {
    const abilities = useAgencyOpeningAbilities();
    const [cycles, setCycles] = useState([]);
    const [applications, setApplications] = useState([]);
    const [selectedCycleId, setSelectedCycleId] = useState("");
    const [loading, setLoading] = useState(true);
    const [applicationsLoading, setApplicationsLoading] = useState(false);
    const [error, setError] = useState("");
    const [drawerOpen, setDrawerOpen] = useState(false);
    const [saving, setSaving] = useState(false);
    const [form, setForm] = useState(emptyForm);
    const [toast, setToast] = useState("");

    useEffect(() => {
        reloadCycles();
    }, []);

    useEffect(() => {
        reloadApplications(selectedCycleId);
    }, [selectedCycleId]);

    async function reloadCycles() {
        setLoading(true);
        setError("");
        try {
            const result = await listAgencyOpeningCycles({ page_size: 100 });
            const items = result.items || [];
            setCycles(items);
            setSelectedCycleId((current) => current || items[0]?.cycleId || "");
        } catch (err) {
            setError(err instanceof Error ? err.message : "加载失败");
        } finally {
            setLoading(false);
        }
    }

    async function reloadApplications(cycleId) {
        setApplicationsLoading(true);
        try {
            const result = await listAgencyOpeningApplications({
                cycle_id: cycleId || undefined,
                page_size: 100,
            });
            setApplications(result.items || []);
        } catch {
            setApplications([]);
        } finally {
            setApplicationsLoading(false);
        }
    }

    function openCreate() {
        setForm(emptyForm);
        setDrawerOpen(true);
    }

    function openEdit(cycle) {
        setForm({
            cycleId: cycle.cycleId,
            title: cycle.title,
            status: cycle.status || "draft",
            startMs: cycle.startMs || "",
            endMs: cycle.endMs || "",
            minHostCount: String(cycle.minHostCount || 10),
            maxAgencyAgeDays: String(cycle.maxAgencyAgeDays || 0),
            rewards: (cycle.rewards?.length ? cycle.rewards : emptyForm.rewards).map((reward) => ({
                rankNo: reward.rankNo,
                thresholdCoinSpent: String(reward.thresholdCoinSpent || ""),
                rewardCoinAmount: String(reward.rewardCoinAmount || ""),
            })),
        });
        setDrawerOpen(true);
    }

    async function submitForm(event) {
        event.preventDefault();
        if (!abilities.canCreate && !form.cycleId) return;
        if (!abilities.canUpdate && form.cycleId) return;
        setSaving(true);
        try {
            const startMs = Number(form.startMs || 0);
            const endMs = Number(form.endMs || 0);
            if (startMs <= 0 || endMs <= 0) {
                throw new Error("请选择活动开始和结束时间");
            }
            if (endMs <= startMs) {
                throw new Error("结束时间必须晚于开始时间");
            }
            const payload = {
                cycle_id: form.cycleId || undefined,
                title: form.title.trim(),
                status: form.status,
                start_ms: startMs,
                end_ms: endMs,
                min_host_count: Number(form.minHostCount || 0),
                max_agency_age_days: Number(form.maxAgencyAgeDays || 0),
                rewards: normalizeRewardPayload(form.rewards),
            };
            if (form.cycleId) {
                await updateAgencyOpeningCycle(form.cycleId, payload);
            } else {
                await createAgencyOpeningCycle(payload);
            }
            setToast("已保存代理开业活动周期");
            setDrawerOpen(false);
            await reloadCycles();
        } catch (err) {
            setToast(err instanceof Error ? err.message : "保存失败");
        } finally {
            setSaving(false);
        }
    }

    async function toggleStatus(cycle) {
        if (!abilities.canUpdate) return;
        const nextStatus = cycle.status === "active" ? "disabled" : "active";
        try {
            await setAgencyOpeningCycleStatus(cycle.cycleId, nextStatus);
            setToast(nextStatus === "active" ? "已启用" : "已停用");
            await reloadCycles();
        } catch (err) {
            setToast(err instanceof Error ? err.message : "状态更新失败");
        }
    }

    async function approveApplication(item) {
        if (!abilities.canUpdate || item.status !== "applied") return;
        try {
            await approveAgencyOpeningApplication(item.applicationId);
            setToast("已同意申请，计分窗口从当前时间开始");
            await reloadApplications(selectedCycleId);
        } catch (err) {
            setToast(err instanceof Error ? err.message : "同意申请失败");
        }
    }

    function updateReward(index, field, value) {
        setForm((current) => ({
            ...current,
            rewards: current.rewards.map((reward, itemIndex) =>
                itemIndex === index ? { ...reward, [field]: value } : reward,
            ),
        }));
    }

    function addRewardTier() {
        setForm((current) => ({
            ...current,
            rewards: [
                ...current.rewards,
                {
                    rankNo: current.rewards.length + 1,
                    thresholdCoinSpent: "",
                    rewardCoinAmount: "",
                },
            ],
        }));
    }

    function removeRewardTier(index) {
        setForm((current) => ({
            ...current,
            rewards: current.rewards
                .filter((_, itemIndex) => itemIndex !== index)
                .map((reward, itemIndex) => ({ ...reward, rankNo: itemIndex + 1 })),
        }));
    }

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <>
                        <Button startIcon={<RefreshOutlined fontSize="small" />} onClick={reloadCycles}>
                            刷新
                        </Button>
                        {abilities.canCreate ? (
                            <Button startIcon={<AddOutlined fontSize="small" />} variant="primary" onClick={openCreate}>
                                新增周期
                            </Button>
                        ) : null}
                    </>
                }
            />
            <DataState error={error} loading={loading} onRetry={reloadCycles}>
                <AdminListBody>
                    <DataTable
                        columns={[
                            {
                                key: "cycle",
                                label: "周期",
                                width: "minmax(260px, 1fr)",
                                render: (cycle) => (
                                    <div className="weekly-star-list-stack">
                                        <span className="weekly-star-list-title">{cycle.title || "-"}</span>
                                        <span className="weekly-star-list-meta">{cycle.cycleId || "-"}</span>
                                    </div>
                                ),
                            },
                            {
                                key: "time",
                                label: "时间",
                                width: "minmax(240px, 0.9fr)",
                                render: (cycle) => (
                                    <div className="weekly-star-list-stack">
                                        <TimeText value={cycle.startMs} />
                                        <span className="weekly-star-list-meta">
                                            至 <TimeText value={cycle.endMs} />
                                        </span>
                                    </div>
                                ),
                            },
                            {
                                key: "policy",
                                label: "规则",
                                width: "minmax(200px, 0.8fr)",
                                render: (cycle) => (
                                    <div className="weekly-star-list-stack">
                                        <span>主播数 &gt; {cycle.minHostCount}</span>
                                        <span className="weekly-star-list-meta">
                                            新代理 {cycle.maxAgencyAgeDays || 0} 天内
                                        </span>
                                    </div>
                                ),
                            },
                            {
                                key: "rewards",
                                label: "金币奖励",
                                width: "minmax(260px, 1fr)",
                                render: (cycle) => (
                                    <div className="weekly-star-list-chip-list">
                                        {(cycle.rewards || []).map((reward) => (
                                            <Chip
                                                className="weekly-star-list-chip"
                                                key={reward.rankNo}
                                                label={`流水≥${formatNumber(reward.thresholdCoinSpent)}: ${formatNumber(reward.rewardCoinAmount)}`}
                                                size="small"
                                                variant="outlined"
                                            />
                                        ))}
                                    </div>
                                ),
                            },
                            {
                                key: "status",
                                label: "状态",
                                width: "112px",
                                render: (cycle) => (
                                    <Chip
                                        color={statusColor(cycle.status)}
                                        label={statusLabel(cycle.status)}
                                        size="small"
                                    />
                                ),
                            },
                            {
                                key: "actions",
                                label: "操作",
                                width: "132px",
                                fixed: "right",
                                resizable: false,
                                render: (cycle) => (
                                    <AdminRowActions>
                                        <AdminActionIconButton
                                            icon={<VisibilityOutlined fontSize="small" />}
                                            label="申请记录"
                                            onClick={() => setSelectedCycleId(cycle.cycleId)}
                                        />
                                        {abilities.canUpdate ? (
                                            <AdminActionIconButton
                                                icon={<EditOutlined fontSize="small" />}
                                                label="编辑"
                                                onClick={() => openEdit(cycle)}
                                            />
                                        ) : null}
                                        {abilities.canUpdate ? (
                                            <Button
                                                size="small"
                                                variant={cycle.status === "active" ? "secondary" : "primary"}
                                                onClick={() => toggleStatus(cycle)}
                                            >
                                                {cycle.status === "active" ? "停用" : "启用"}
                                            </Button>
                                        ) : null}
                                    </AdminRowActions>
                                ),
                            },
                        ]}
                        emptyLabel="暂无代理开业活动周期"
                        items={cycles}
                        minWidth="1220px"
                        rowKey={(cycle) => cycle.cycleId}
                    />
                </AdminListBody>
            </DataState>

            <AdminListBody>
                <Typography component="h2" variant="h6">
                    申请记录
                </Typography>
                <DataTable
                    columns={[
                        {
                            key: "agency",
                            label: "Agency",
                            width: "minmax(220px, 1fr)",
                            render: (item) => `${item.agencyName || "-"} / ${item.agencyId || "-"}`,
                        },
                        {
                            key: "owner",
                            label: "Owner",
                            width: "160px",
                            render: (item) => item.agencyOwnerUserId || "-",
                        },
                        { key: "hosts", label: "主播数", width: "100px", render: (item) => item.hostCount },
                        {
                            key: "score",
                            label: "开业流水",
                            width: "120px",
                            render: (item) => formatNumber(item.scoreCoinAmount),
                        },
                        {
                            key: "reward",
                            label: "奖励",
                            width: "180px",
                            render: (item) =>
                                item.rewardCoinAmount
                                    ? `流水≥${formatNumber(item.rewardThresholdCoinSpent)} / ${formatNumber(item.rewardCoinAmount)}`
                                    : "-",
                        },
                        {
                            key: "status",
                            label: "状态",
                            width: "112px",
                            render: (item) => <Chip label={applicationStatusLabel(item.status)} size="small" />,
                        },
                        {
                            key: "applied",
                            label: "申请时间",
                            width: "180px",
                            render: (item) => <TimeText value={item.appliedAtMs} />,
                        },
                        {
                            key: "score-window",
                            label: "计分窗口",
                            width: "240px",
                            render: (item) =>
                                item.scoreStartMs ? (
                                    <div className="weekly-star-list-stack">
                                        <TimeText value={item.scoreStartMs} />
                                        <span className="weekly-star-list-meta">
                                            至 <TimeText value={item.scoreEndMs} />
                                        </span>
                                    </div>
                                ) : (
                                    "-"
                                ),
                        },
                        {
                            key: "granted",
                            label: "发奖时间",
                            width: "180px",
                            render: (item) => (item.grantedAtMs ? <TimeText value={item.grantedAtMs} /> : "-"),
                        },
                        {
                            key: "actions",
                            label: "操作",
                            width: "112px",
                            fixed: "right",
                            resizable: false,
                            render: (item) =>
                                item.status === "applied" && abilities.canUpdate ? (
                                    <AdminRowActions>
                                        <Button
                                            size="small"
                                            startIcon={<CheckCircleOutlineOutlined fontSize="small" />}
                                            variant="primary"
                                            onClick={() => approveApplication(item)}
                                        >
                                            同意
                                        </Button>
                                    </AdminRowActions>
                                ) : (
                                    "-"
                                ),
                        },
                    ]}
                    emptyLabel={applicationsLoading ? "加载中..." : "暂无申请记录"}
                    items={applications}
                    minWidth="1560px"
                    rowKey={(item) => item.applicationId}
                />
            </AdminListBody>

            <Drawer anchor="right" open={drawerOpen} onClose={() => setDrawerOpen(false)}>
                <Box className="weekly-star-config-drawer" component="form" onSubmit={submitForm}>
                    <div className="weekly-star-config-drawer__header">
                        <h2 className="weekly-star-config-drawer__title">
                            {form.cycleId ? "编辑代理开业活动" : "新增代理开业活动"}
                        </h2>
                    </div>
                    <div className="weekly-star-config-drawer__body">
                        <section className="weekly-star-config-section">
                            <div className="weekly-star-config-grid weekly-star-config-grid--basic">
                                <TextField
                                    label="标题"
                                    required
                                    value={form.title}
                                    onChange={(event) => setForm({ ...form, title: event.target.value })}
                                />
                                <TextField
                                    label="状态"
                                    select
                                    value={form.status}
                                    onChange={(event) => setForm({ ...form, status: event.target.value })}
                                >
                                    {statusOptions.slice(0, 3).map(([value, label]) => (
                                        <MenuItem key={value} value={value}>
                                            {label}
                                        </MenuItem>
                                    ))}
                                </TextField>
                                <div className="weekly-star-time-range">
                                    <TimeRangeFilter
                                        className="weekly-star-time-range__control"
                                        label="活动时间"
                                        value={{ endMs: form.endMs, startMs: form.startMs }}
                                        onChange={(range) =>
                                            setForm({ ...form, endMs: range.endMs, startMs: range.startMs })
                                        }
                                    />
                                </div>
                                <TextField
                                    label="主播数必须大于"
                                    required
                                    type="number"
                                    value={form.minHostCount}
                                    onChange={(event) => setForm({ ...form, minHostCount: event.target.value })}
                                />
                                <TextField
                                    label="代理创建天数上限"
                                    type="number"
                                    value={form.maxAgencyAgeDays}
                                    onChange={(event) => setForm({ ...form, maxAgencyAgeDays: event.target.value })}
                                />
                            </div>
                        </section>
                        <section className="weekly-star-config-section">
                            <Typography component="h3" variant="subtitle1">
                                开业流水档位奖励
                            </Typography>
                            <Box sx={{ mb: 2 }}>
                                <Button
                                    startIcon={<AddOutlined fontSize="small" />}
                                    type="button"
                                    onClick={addRewardTier}
                                >
                                    添加档位
                                </Button>
                            </Box>
                            <div className="weekly-star-config-card-grid">
                                {form.rewards.map((reward, index) => (
                                    <div className="weekly-star-config-card" key={reward.rankNo}>
                                        <div className="weekly-star-config-card__header">
                                            <span
                                                className={`weekly-star-rank-badge weekly-star-rank-badge--${index + 1}`}
                                            >
                                                档位 {index + 1}
                                            </span>
                                            {form.rewards.length > 1 ? (
                                                <Button
                                                    startIcon={<DeleteOutlineOutlined fontSize="small" />}
                                                    type="button"
                                                    onClick={() => removeRewardTier(index)}
                                                >
                                                    删除
                                                </Button>
                                            ) : null}
                                        </div>
                                        <TextField
                                            fullWidth
                                            label="开业流水"
                                            required
                                            type="number"
                                            value={reward.thresholdCoinSpent}
                                            onChange={(event) =>
                                                updateReward(index, "thresholdCoinSpent", event.target.value)
                                            }
                                        />
                                        <TextField
                                            fullWidth
                                            label="奖励金币"
                                            required
                                            type="number"
                                            value={reward.rewardCoinAmount}
                                            onChange={(event) =>
                                                updateReward(index, "rewardCoinAmount", event.target.value)
                                            }
                                        />
                                    </div>
                                ))}
                            </div>
                        </section>
                    </div>
                    <div className="weekly-star-config-drawer__actions">
                        <Button onClick={() => setDrawerOpen(false)}>取消</Button>
                        <Button disabled={saving} type="submit" variant="primary">
                            保存
                        </Button>
                    </div>
                </Box>
            </Drawer>

            <Snackbar autoHideDuration={2600} message={toast} open={Boolean(toast)} onClose={() => setToast("")} />
        </AdminListPage>
    );
}

function statusLabel(status) {
    return statusOptions.find(([value]) => value === status)?.[1] || status || "-";
}

function statusColor(status) {
    if (status === "active") return "success";
    if (status === "settled") return "info";
    if (status === "settling") return "warning";
    if (status === "disabled") return "default";
    return "secondary";
}

function applicationStatusLabel(status) {
    return (
        {
            applied: "待审核",
            approved: "计分中",
            pending: "待发奖",
            granted: "已发奖",
            failed: "发奖失败",
            expired: "已过期",
        }[status] ||
        status ||
        "-"
    );
}

function normalizeRewardPayload(rewards) {
    const payload = (rewards || []).map((reward, index) => {
        const thresholdCoinSpent = Number(reward.thresholdCoinSpent || 0);
        const rewardCoinAmount = Number(reward.rewardCoinAmount || 0);
        if (!Number.isInteger(thresholdCoinSpent) || thresholdCoinSpent <= 0) {
            throw new Error("开业流水必须是大于 0 的整数");
        }
        if (!Number.isInteger(rewardCoinAmount) || rewardCoinAmount < 0) {
            throw new Error("奖励金币不能小于 0");
        }
        return {
            rank_no: index + 1,
            tier_no: index + 1,
            threshold_coin_spent: thresholdCoinSpent,
            reward_coin_amount: rewardCoinAmount,
        };
    });
    for (let index = 1; index < payload.length; index += 1) {
        if (payload[index].threshold_coin_spent <= payload[index - 1].threshold_coin_spent) {
            throw new Error("开业流水档位必须递增");
        }
    }
    if (!payload.length) {
        throw new Error("至少需要配置一个开业流水档位");
    }
    return payload;
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString();
}
