import AddOutlined from "@mui/icons-material/AddOutlined";
import BarChartOutlined from "@mui/icons-material/BarChartOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import EventAvailableOutlined from "@mui/icons-material/EventAvailableOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import WorkspacePremiumOutlined from "@mui/icons-material/WorkspacePremiumOutlined";
import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import Drawer from "@mui/material/Drawer";
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import Snackbar from "@mui/material/Snackbar";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useEffect, useMemo, useState } from "react";
import {
    createWeeklyStarCycle,
    listWeeklyStarCycles,
    listWeeklyStarLeaderboard,
    listWeeklyStarSettlements,
    setWeeklyStarCycleStatus,
    updateWeeklyStarCycle,
} from "@/features/weekly-star/api";
import { listGifts, listResourceGroups } from "@/features/resources/api";
import { GiftSelectField } from "@/features/resources/components/GiftSelectDrawer.jsx";
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 { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { RegionSelect } from "@/shared/ui/RegionSelect.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";

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

const emptyForm = {
    cycleId: "",
    title: "Weekly Star",
    regionId: "0",
    status: "draft",
    startMs: "",
    endMs: "",
    giftIds: ["", "", ""],
    resourceGroupIds: ["", "", ""],
};

export function WeeklyStarPage() {
    const [cycles, setCycles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    const [drawerOpen, setDrawerOpen] = useState(false);
    const [saving, setSaving] = useState(false);
    const [form, setForm] = useState(emptyForm);
    const [gifts, setGifts] = useState([]);
    const [resourceGroups, setResourceGroups] = useState([]);
    const [toast, setToast] = useState("");
    const [leaderboard, setLeaderboard] = useState({ cycle: null, loading: false, items: [], error: "" });
    const [settlements, setSettlements] = useState({ cycle: null, loading: false, items: [], error: "" });
    const { loadingRegions, regionOptions } = useRegionOptions();

    const giftOptions = useMemo(
        () =>
            gifts.map((gift) => ({
                label: gift.name ? `${gift.name} · ${gift.giftId}` : String(gift.giftId || ""),
                value: String(gift.giftId || ""),
            })),
        [gifts],
    );
    const resourceGroupOptions = useMemo(
        () =>
            resourceGroups.map((group) => ({
                label: group.name ? `${group.name} · ${group.groupId}` : String(group.groupId || ""),
                value: String(group.groupId || ""),
            })),
        [resourceGroups],
    );
    const weeklyStarRegionOptions = useMemo(
        () => [{ label: "默认区域 · 0", name: "默认区域", regionId: 0, value: "0" }, ...regionOptions],
        [regionOptions],
    );

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

    function reloadCycles() {
        setLoading(true);
        setError("");
        listWeeklyStarCycles({ page_size: 100 })
            .then((page) => {
                setCycles(page.items || []);
            })
            .catch((err) => {
                setError(err.message || "加载周星配置失败");
            })
            .finally(() => {
                setLoading(false);
            });
    }

    function loadOptions() {
        Promise.allSettled([
            listGifts({ status: "active", page_size: 200 }),
            listResourceGroups({ status: "active", page_size: 200 }),
        ]).then(([giftResult, groupResult]) => {
            if (giftResult.status === "fulfilled") {
                setGifts(giftResult.value.items || []);
            }
            if (groupResult.status === "fulfilled") {
                setResourceGroups(groupResult.value.items || []);
            }
        });
    }

    function openCreate() {
        const now = Date.now();
        setForm({
            ...emptyForm,
            startMs: now,
            endMs: now + 7 * 24 * 60 * 60 * 1000,
        });
        setDrawerOpen(true);
    }

    function openEdit(cycle) {
        const rewards = [1, 2, 3].map((rankNo) =>
            String(cycle.rewards.find((item) => item.rankNo === rankNo)?.resourceGroupId || ""),
        );
        setForm({
            cycleId: cycle.cycleId,
            title: cycle.title || "Weekly Star",
            regionId: String(cycle.regionId || 0),
            status: cycle.status || "draft",
            startMs: cycle.startMs || "",
            endMs: cycle.endMs || "",
            giftIds: [0, 1, 2].map((index) => String(cycle.gifts[index]?.giftId || "")),
            resourceGroupIds: rewards,
        });
        setDrawerOpen(true);
    }

    function closeDrawer() {
        if (!saving) {
            setDrawerOpen(false);
        }
    }

    function updateGift(index, value) {
        setForm((current) => ({
            ...current,
            giftIds: current.giftIds.map((item, itemIndex) => (itemIndex === index ? value : item)),
        }));
    }

    function updateReward(index, value) {
        setForm((current) => ({
            ...current,
            resourceGroupIds: current.resourceGroupIds.map((item, itemIndex) => (itemIndex === index ? value : item)),
        }));
    }

    function updateTimeRange(value) {
        setForm((current) => ({
            ...current,
            endMs: value?.endMs || "",
            startMs: value?.startMs || "",
        }));
    }

    async function submitForm(event) {
        event.preventDefault();
        const payload = buildPayload(form);
        if (!payload) {
            return;
        }
        setSaving(true);
        try {
            if (form.cycleId) {
                await updateWeeklyStarCycle(form.cycleId, payload);
                setToast("周星配置已更新");
            } else {
                await createWeeklyStarCycle(payload);
                setToast("周星配置已创建");
            }
            setDrawerOpen(false);
            reloadCycles();
        } catch (err) {
            setToast(err.message || "保存失败");
        } finally {
            setSaving(false);
        }
    }

    function buildPayload(values) {
        const giftIds = values.giftIds.map((item) => String(item || "").trim()).filter(Boolean);
        const resourceGroupIds = values.resourceGroupIds.map((item) => Number(item || 0));
        const startMs = Number(values.startMs || 0);
        const endMs = Number(values.endMs || 0);
        if (!values.title.trim()) {
            setToast("请填写活动标题");
            return null;
        }
        if (giftIds.length !== 3 || new Set(giftIds).size !== 3) {
            setToast("请选择 3 个不同礼物");
            return null;
        }
        if (resourceGroupIds.some((item) => !Number.isFinite(item) || item <= 0)) {
            setToast("请填写 Top1/Top2/Top3 资源组 ID");
            return null;
        }
        if (!startMs || !endMs || endMs <= startMs) {
            setToast("请填写有效时间范围");
            return null;
        }
        return {
            title: values.title.trim(),
            status: values.status || "draft",
            region_id: Number(values.regionId || 0),
            start_ms: startMs,
            end_ms: endMs,
            gift_ids: giftIds,
            top1_resource_group_id: resourceGroupIds[0],
            top2_resource_group_id: resourceGroupIds[1],
            top3_resource_group_id: resourceGroupIds[2],
        };
    }

    async function toggleStatus(cycle) {
        const nextStatus = cycle.status === "active" ? "disabled" : "active";
        try {
            await setWeeklyStarCycleStatus(cycle.cycleId, nextStatus);
            setToast(nextStatus === "active" ? "配置已启用" : "配置已停用");
            reloadCycles();
        } catch (err) {
            setToast(err.message || "状态更新失败");
        }
    }

    async function openLeaderboard(cycle) {
        setLeaderboard({ cycle, loading: true, items: [], error: "" });
        try {
            const result = await listWeeklyStarLeaderboard(cycle.cycleId);
            setLeaderboard({ cycle, loading: false, items: result.items || [], error: "" });
        } catch (err) {
            setLeaderboard({ cycle, loading: false, items: [], error: err.message || "加载排行榜失败" });
        }
    }

    async function openSettlements(cycle) {
        setSettlements({ cycle, loading: true, items: [], error: "" });
        try {
            const result = await listWeeklyStarSettlements(cycle.cycleId);
            setSettlements({ cycle, loading: false, items: result || [], error: "" });
        } catch (err) {
            setSettlements({ cycle, loading: false, items: [], error: err.message || "加载结算结果失败" });
        }
    }

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <>
                        <Button startIcon={<RefreshOutlined fontSize="small" />} onClick={reloadCycles}>
                            刷新
                        </Button>
                        <Button startIcon={<AddOutlined fontSize="small" />} variant="primary" onClick={openCreate}>
                            新增周期
                        </Button>
                    </>
                }
            />
            <DataState error={error} loading={loading} onRetry={reloadCycles}>
                <AdminListBody>
                    <DataTable
                        columns={[
                            {
                                key: "cycle",
                                label: "周期",
                                width: "minmax(280px, 1.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: "region",
                                label: "区域",
                                width: "120px",
                                render: (cycle) => regionLabel(cycle.regionId, weeklyStarRegionOptions),
                            },
                            {
                                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: "gifts",
                                label: "礼物",
                                width: "minmax(260px, 1fr)",
                                render: (cycle) => (
                                    <WeeklyStarChipList
                                        items={(cycle.gifts || []).map((gift) => ({
                                            key: gift.giftId,
                                            label: giftLabel(gift.giftId, giftOptions),
                                        }))}
                                    />
                                ),
                            },
                            {
                                key: "rewards",
                                label: "奖励资源组",
                                width: "minmax(240px, 0.8fr)",
                                render: (cycle) => (
                                    <WeeklyStarChipList
                                        outlined
                                        items={(cycle.rewards || []).map((reward) => ({
                                            key: reward.rankNo,
                                            label: `Top${reward.rankNo}: ${groupLabel(
                                                reward.resourceGroupId,
                                                resourceGroupOptions,
                                            )}`,
                                        }))}
                                    />
                                ),
                            },
                            {
                                key: "status",
                                label: "状态",
                                width: "112px",
                                render: (cycle) => (
                                    <Chip color={statusColor(cycle.status)} label={statusLabel(cycle.status)} size="small" />
                                ),
                            },
                            {
                                key: "actions",
                                label: "操作",
                                width: "112px",
                                fixed: "right",
                                resizable: false,
                                render: (cycle) => (
                                    <WeeklyStarRowActions
                                        cycle={cycle}
                                        onEdit={openEdit}
                                        onLeaderboard={openLeaderboard}
                                        onSettlements={openSettlements}
                                        onToggleStatus={toggleStatus}
                                    />
                                ),
                            },
                        ]}
                        emptyLabel="暂无周星周期配置"
                        items={cycles}
                        minWidth="1460px"
                        rowKey={(cycle) => cycle.cycleId}
                    />
                </AdminListBody>
            </DataState>

            <Drawer anchor="right" open={drawerOpen} onClose={closeDrawer}>
                <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="form-drawer__section-title">基础信息</div>
                            <div className="weekly-star-config-grid weekly-star-config-grid--basic">
                                <TextField
                                    required
                                    label="活动标题"
                                    value={form.title}
                                    onChange={(event) =>
                                        setForm((current) => ({ ...current, title: event.target.value }))
                                    }
                                />
                                <RegionSelect
                                    required
                                    label="区域"
                                    loading={loadingRegions}
                                    options={weeklyStarRegionOptions}
                                    size="medium"
                                    value={form.regionId}
                                    onChange={(value) =>
                                        setForm((current) => ({ ...current, regionId: value || "0" }))
                                    }
                                />
                                <FormControl>
                                    <InputLabel>状态</InputLabel>
                                    <Select
                                        label="状态"
                                        value={form.status}
                                        onChange={(event) =>
                                            setForm((current) => ({ ...current, status: event.target.value }))
                                        }
                                    >
                                        {statusOptions.map(([value, label]) => (
                                            <MenuItem key={value} value={value}>
                                                {label}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                            </div>
                            <div className="weekly-star-time-range">
                                <TimeRangeFilter
                                    className="weekly-star-time-range__control"
                                    label="活动时间"
                                    value={{ endMs: form.endMs, startMs: form.startMs }}
                                    onChange={updateTimeRange}
                                />
                            </div>
                        </section>
                        <section className="weekly-star-config-section">
                            <div className="form-drawer__section-title">活动礼物</div>
                            <div className="weekly-star-config-card-grid">
                                {[0, 1, 2].map((index) => (
                                    <div className="weekly-star-config-card" key={index}>
                                        <div className="weekly-star-config-card__header">
                                            <span className="weekly-star-config-card__label">礼物 {index + 1}</span>
                                        </div>
                                        <GiftSelectField
                                            drawerTitle={`选择礼物 ${index + 1}`}
                                            gifts={gifts}
                                            label="选择礼物"
                                            placeholder="搜索礼物名称或 ID"
                                            value={form.giftIds[index]}
                                            onChange={(value) => updateGift(index, value)}
                                        />
                                    </div>
                                ))}
                            </div>
                        </section>
                        <section className="weekly-star-config-section">
                            <div className="form-drawer__section-title">排名奖励</div>
                            <div className="weekly-star-config-card-grid">
                                {[0, 1, 2].map((index) => (
                                    <div className="weekly-star-config-card" key={index}>
                                        <div className="weekly-star-config-card__header">
                                            <span className={`weekly-star-rank-badge weekly-star-rank-badge--${index + 1}`}>
                                                Top{index + 1}
                                            </span>
                                        </div>
                                        <ResourceGroupSelectField
                                            drawerTitle={`选择 Top${index + 1} 奖励资源组`}
                                            groups={resourceGroups}
                                            label="奖励资源组"
                                            placeholder="搜索资源组名称或 ID"
                                            value={form.resourceGroupIds[index]}
                                            onChange={(value) => updateReward(index, value)}
                                        />
                                    </div>
                                ))}
                            </div>
                        </section>
                    </div>
                    <div className="weekly-star-config-drawer__actions">
                        <Button disabled={saving} type="button" onClick={closeDrawer}>
                            取消
                        </Button>
                        <Button
                            disabled={saving}
                            startIcon={<EventAvailableOutlined fontSize="small" />}
                            type="submit"
                            variant="primary"
                        >
                            保存
                        </Button>
                    </div>
                </Box>
            </Drawer>

            <ResultDialog
                columns={["排名", "用户 ID", "积分", "首次计分时间", "最后计分时间"]}
                emptyText="暂无排行榜数据"
                error={leaderboard.error}
                loading={leaderboard.loading}
                open={Boolean(leaderboard.cycle)}
                rows={leaderboard.items}
                title={leaderboard.cycle ? `排行榜 · ${leaderboard.cycle.title}` : "排行榜"}
                onClose={() => setLeaderboard({ cycle: null, loading: false, items: [], error: "" })}
                renderRow={(item) => [
                    item.rankNo,
                    item.userId,
                    formatNumber(item.score),
                    <TimeText value={item.firstScoredAtMs} />,
                    <TimeText value={item.lastScoredAtMs} />,
                ]}
            />
            <ResultDialog
                columns={["排名", "用户 ID", "积分", "资源组", "状态", "钱包命令"]}
                emptyText="暂无结算结果"
                error={settlements.error}
                loading={settlements.loading}
                open={Boolean(settlements.cycle)}
                rows={settlements.items}
                title={settlements.cycle ? `结算结果 · ${settlements.cycle.title}` : "结算结果"}
                onClose={() => setSettlements({ cycle: null, loading: false, items: [], error: "" })}
                renderRow={(item) => [
                    item.rankNo,
                    item.userId,
                    formatNumber(item.score),
                    groupLabel(item.resourceGroupId, resourceGroupOptions),
                    item.status || "-",
                    item.walletCommandId || "-",
                ]}
            />
            <Snackbar autoHideDuration={3200} open={Boolean(toast)} onClose={() => setToast("")}>
                <Alert severity="info" variant="filled" onClose={() => setToast("")}>
                    {toast}
                </Alert>
            </Snackbar>
        </AdminListPage>
    );
}

function WeeklyStarChipList({ items, outlined = false }) {
    return (
        <div className="weekly-star-list-chip-list">
            {items.length ? (
                items.map((item) => (
                    <Chip
                        className="weekly-star-list-chip"
                        key={item.key}
                        label={item.label || "-"}
                        size="small"
                        variant={outlined ? "outlined" : "filled"}
                    />
                ))
            ) : (
                <span className="weekly-star-list-meta">-</span>
            )}
        </div>
    );
}

function WeeklyStarRowActions({ cycle, onEdit, onLeaderboard, onSettlements, onToggleStatus }) {
    const toggleDisabled = cycle.status === "settled" || cycle.status === "settling";
    const toggleLabel = cycle.status === "active" ? "停用周期" : "启用周期";
    return (
        <div className="weekly-star-list-actions">
            <AdminRowActions>
                <AdminActionIconButton label="编辑周期" onClick={() => onEdit(cycle)}>
                    <EditOutlined fontSize="small" />
                </AdminActionIconButton>
                <AdminActionIconButton disabled={toggleDisabled} label={toggleLabel} onClick={() => onToggleStatus(cycle)}>
                    <EventAvailableOutlined fontSize="small" />
                </AdminActionIconButton>
                <AdminActionIconButton label="排行榜" onClick={() => onLeaderboard(cycle)}>
                    <BarChartOutlined fontSize="small" />
                </AdminActionIconButton>
                <AdminActionIconButton label="结算结果" onClick={() => onSettlements(cycle)}>
                    <WorkspacePremiumOutlined fontSize="small" />
                </AdminActionIconButton>
            </AdminRowActions>
        </div>
    );
}

function ResultDialog({ columns, emptyText, error, loading, onClose, open, renderRow, rows, title }) {
    return (
        <Drawer anchor="right" open={open} PaperProps={{ sx: { width: 720 } }} onClose={onClose}>
            <Box sx={{ p: 3 }}>
                <Typography sx={{ mb: 2 }} variant="h6">
                    {title}
                </Typography>
                {loading ? (
                    <Typography color="text.secondary">加载中...</Typography>
                ) : error ? (
                    <Alert severity="error">{error}</Alert>
                ) : (
                    <TableContainer>
                        <Table size="small">
                            <TableHead>
                                <TableRow>
                                    {columns.map((column) => (
                                        <TableCell key={column}>{column}</TableCell>
                                    ))}
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {rows.map((row, rowIndex) => (
                                    <TableRow key={`${row.userId || row.settlementId || rowIndex}-${rowIndex}`}>
                                        {renderRow(row).map((cell, cellIndex) => (
                                            <TableCell key={cellIndex}>{cell}</TableCell>
                                        ))}
                                    </TableRow>
                                ))}
                                {!rows.length ? (
                                    <TableRow>
                                        <TableCell colSpan={columns.length}>
                                            <Box sx={{ py: 5, textAlign: "center", color: "text.secondary" }}>
                                                {emptyText}
                                            </Box>
                                        </TableCell>
                                    </TableRow>
                                ) : null}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}
            </Box>
        </Drawer>
    );
}

function giftLabel(giftId, options) {
    return options.find((option) => option.value === String(giftId))?.label || giftId || "-";
}

function groupLabel(groupId, options) {
    return options.find((option) => option.value === String(groupId))?.label || groupId || "-";
}

function regionLabel(regionId, options) {
    const value = String(regionId ?? "0");
    const option = options.find((item) => item.value === value);
    return option?.name || option?.label || (value === "0" ? "默认区域" : `区域 ${value}`);
}

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

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

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