import EditOutlined from "@mui/icons-material/EditOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import SettingsOutlined from "@mui/icons-material/SettingsOutlined";
import CircularProgress from "@mui/material/CircularProgress";
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 { useMemo } from "react";
import { cpWeeklyRankRanks, useCPWeeklyRankPage } from "@/features/cp-weekly-rank/hooks/useCPWeeklyRankPage.js";
import styles from "@/features/cp-weekly-rank/cp-weekly-rank.module.css";
import { AdminListBody, AdminListPage, AdminListToolbar } from "@/shared/ui/AdminListLayout.jsx";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";

export function CPWeeklyRankPage() {
    const page = useCPWeeklyRankPage();
    const resourceLabels = useMemo(() => groupLabelMap(page.resourceGroups), [page.resourceGroups]);
    const columns = useMemo(() => settlementColumns(resourceLabels), [resourceLabels]);

    return (
        <AdminListPage>
            <div className={styles.summaryPanel}>
                <div className={styles.summaryItems}>
                    <SummaryItem label="活动编码">{page.config.activityCode || "cp_weekly_rank"}</SummaryItem>
                    <SummaryItem label="活动状态">{page.config.enabled === false ? "停用" : "启用"}</SummaryItem>
                    <SummaryItem label="奖励名次">Top {page.config.topCount || 3}</SummaryItem>
                    <SummaryItem label="已配置奖励">{page.configuredRewardCount} / 3</SummaryItem>
                    <SummaryItem label="最近更新">
                        {page.config.updatedAtMs ? <TimeText value={page.config.updatedAtMs} /> : "-"}
                    </SummaryItem>
                </div>
                <div className={styles.summaryActions}>
                    <Button
                        disabled={page.loading}
                        startIcon={<RefreshOutlined fontSize="small" />}
                        onClick={page.reload}
                    >
                        刷新
                    </Button>
                    <Button
                        disabled={page.loading}
                        startIcon={
                            page.abilities.canUpdate ? (
                                <EditOutlined fontSize="small" />
                            ) : (
                                <SettingsOutlined fontSize="small" />
                            )
                        }
                        variant="primary"
                        onClick={page.openDrawer}
                    >
                        配置
                    </Button>
                </div>
            </div>
            <RewardPreview config={page.config} resourceLabels={resourceLabels} />
            <AdminListToolbar
                actions={
                    <Button
                        disabled={page.settlementsLoading}
                        startIcon={<RefreshOutlined fontSize="small" />}
                        onClick={() => page.reloadSettlements(page.settlementRange)}
                    >
                        刷新记录
                    </Button>
                }
                filters={
                    <TimeRangeFilter label="结算周期" value={page.settlementRange} onChange={page.setSettlementRange} />
                }
            />
            <DataState
                error={page.settlementsError}
                loading={page.settlementsLoading}
                onRetry={() => page.reloadSettlements(page.settlementRange)}
            >
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        emptyLabel="当前无数据"
                        items={page.settlements.items}
                        minWidth="1320px"
                        rowKey={(item) => item.settlementId || `${item.relationshipId}-${item.userId}`}
                    />
                </AdminListBody>
            </DataState>
            <CPWeeklyRankDialog page={page} resourceLabels={resourceLabels} />
        </AdminListPage>
    );
}

function RewardPreview({ config, resourceLabels }) {
    const rewards = completeRewards(config.rewards || []);
    return (
        <div className={styles.rewardStrip}>
            {rewards.map((reward) => (
                <div className={styles.rewardItem} key={reward.rankNo}>
                    <span className={styles.rewardRank}>Top {reward.rankNo}</span>
                    <span className={styles.rewardGroup}>{resourceLabel(resourceLabels, reward.resourceGroupId)}</span>
                </div>
            ))}
        </div>
    );
}

function CPWeeklyRankDialog({ page, resourceLabels }) {
    const canUpdate = page.abilities.canUpdate;
    const disabled = !canUpdate || page.saving || page.loading;
    const enabled = page.form.enabled !== false;
    return (
        <Dialog
            className={styles.configDialog}
            maxWidth={false}
            open={page.drawerOpen}
            slotProps={{ paper: { className: styles.configDialogPaper } }}
            onClose={page.saving ? undefined : page.closeDrawer}
        >
            <form className={styles.configDialogForm} onSubmit={page.submit}>
                <DialogTitle className={styles.configDialogTitle}>
                    <div>
                        <h2>CP排行活动</h2>
                        <span>Top 1-3 资源组会发给获奖 CP 双方</span>
                    </div>
                    <AdminSwitch
                        checked={enabled}
                        checkedLabel="启用"
                        disabled={disabled}
                        label="CP排行活动状态"
                        uncheckedLabel="停用"
                        onChange={(event) => page.updateForm({ enabled: event.target.checked })}
                    />
                </DialogTitle>
                <DialogContent className={styles.configDialogContent}>
                    <div className={styles.rewardEditorList}>
                        {cpWeeklyRankRanks.map((rankNo) => {
                            const reward = (page.form.rewards || []).find(
                                (item) => Number(item.rankNo) === Number(rankNo),
                            ) || {
                                rankNo,
                                resourceGroupId: "",
                            };
                            return (
                                <div className={styles.rewardEditor} key={rankNo}>
                                    <div className={styles.rewardEditorHeader}>
                                        <span>Top {rankNo}</span>
                                        <span>{resourceLabel(resourceLabels, reward.resourceGroupId)}</span>
                                    </div>
                                    <ResourceGroupSelectField
                                        disabled={disabled || !enabled}
                                        drawerTitle={`CP排行活动 Top ${rankNo} 奖励资源组`}
                                        emptyLabel="未配置奖励"
                                        groups={page.resourceGroups}
                                        label="奖励资源组"
                                        placeholder="点击选择奖励资源组"
                                        value={reward.resourceGroupId}
                                        onChange={(value) =>
                                            page.updateReward(rankNo, {
                                                resourceGroupId: value,
                                            })
                                        }
                                    />
                                </div>
                            );
                        })}
                    </div>
                </DialogContent>
                <DialogActions className={styles.configDialogActions}>
                    <Button disabled={page.saving} type="button" onClick={page.closeDrawer}>
                        {canUpdate ? "取消" : "关闭"}
                    </Button>
                    {canUpdate ? (
                        <Button
                            disabled={disabled}
                            startIcon={
                                page.saving ? (
                                    <CircularProgress color="inherit" size={16} />
                                ) : (
                                    <SaveOutlined fontSize="small" />
                                )
                            }
                            type="submit"
                            variant="primary"
                        >
                            保存
                        </Button>
                    ) : null}
                </DialogActions>
            </form>
        </Dialog>
    );
}

function settlementColumns(resourceLabels) {
    return [
        {
            key: "period",
            label: "结算周期",
            width: "minmax(240px, 0.9fr)",
            render: (item) => (
                <span className={styles.periodCell}>
                    <TimeText value={item.periodStartMs} />
                    <span>至</span>
                    <TimeText value={item.periodEndMs} />
                </span>
            ),
        },
        {
            key: "rankNo",
            label: "名次",
            width: "minmax(90px, 0.3fr)",
            render: (item) => `Top ${item.rankNo || "-"}`,
        },
        {
            key: "userId",
            label: "用户ID",
            width: "minmax(140px, 0.45fr)",
            render: (item) => item.userId || "-",
        },
        {
            key: "relationshipId",
            label: "关系ID",
            width: "minmax(220px, 0.75fr)",
            render: (item) => item.relationshipId || "-",
        },
        {
            key: "score",
            label: "周积分",
            width: "minmax(110px, 0.35fr)",
            render: (item) => formatNumber(item.score),
        },
        {
            key: "resourceGroupId",
            label: "奖励资源组",
            width: "minmax(180px, 0.55fr)",
            render: (item) => resourceLabel(resourceLabels, item.resourceGroupId),
        },
        {
            key: "status",
            label: "状态",
            width: "minmax(110px, 0.35fr)",
            render: (item) => <StatusBadge status={item.status} />,
        },
        {
            key: "walletGrantId",
            label: "发放流水",
            width: "minmax(180px, 0.55fr)",
            render: (item) => item.walletGrantId || item.walletCommandId || "-",
        },
        {
            key: "attemptCount",
            label: "重试",
            width: "minmax(90px, 0.3fr)",
            render: (item) => formatNumber(item.attemptCount),
        },
        {
            key: "updatedAt",
            label: "更新时间",
            width: "minmax(170px, 0.55fr)",
            render: (item) => (item.updatedAtMs ? <TimeText value={item.updatedAtMs} /> : "-"),
        },
    ];
}

function StatusBadge({ status }) {
    const normalized = String(status || "").toLowerCase();
    return (
        <span className={[styles.statusBadge, statusClassName(normalized)].filter(Boolean).join(" ")}>
            {statusLabel(normalized)}
        </span>
    );
}

function SummaryItem({ children, label }) {
    return (
        <div className={styles.summaryItem}>
            <span className={styles.summaryLabel}>{label}</span>
            <span className={styles.summaryValue}>{children}</span>
        </div>
    );
}

function completeRewards(rewards) {
    const byRank = new Map((rewards || []).map((reward) => [Number(reward.rankNo), reward]));
    return cpWeeklyRankRanks.map((rankNo) => ({
        rankNo,
        resourceGroupId: Number(byRank.get(rankNo)?.resourceGroupId || 0),
    }));
}

function groupLabelMap(groups) {
    return new Map(
        (groups || []).map((group) => [
            String(group.groupId),
            group.name || group.groupCode || `资源组 #${group.groupId}`,
        ]),
    );
}

function resourceLabel(resourceLabels, value) {
    const normalized = String(value || "");
    return normalized && resourceLabels.has(normalized)
        ? resourceLabels.get(normalized)
        : normalized
          ? `资源组 #${normalized}`
          : "未配置奖励";
}

function statusLabel(status) {
    const labels = {
        failed: "失败",
        granted: "已发放",
        pending: "待发放",
        running: "发放中",
    };
    return labels[status] || status || "-";
}

function statusClassName(status) {
    if (status === "granted") {
        return styles.statusActive;
    }
    if (status === "failed") {
        return styles.statusDanger;
    }
    if (status === "running") {
        return styles.statusPending;
    }
    return styles.statusDisabled;
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString("zh-CN");
}
