import MenuItem from "@mui/material/MenuItem";
import Pagination from "@mui/material/Pagination";
import TextField from "@mui/material/TextField";
import Avatar from "@mui/material/Avatar";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { formatActivityMetric } from "@/features/activity-templates/dataModel.js";
import { formatMillis } from "@/shared/utils/time.js";
import styles from "@/features/activity-templates/activity-templates.module.css";

export function ActivityTemplateLeaderboardPanel({
    boardType,
    data,
    error,
    loading,
    onBoardTypeChange,
    onPageChange,
    onPeriodChange,
    onRetry,
    page,
    periodKey,
    periodOptions,
}) {
    const columns = [
        { key: "rank", label: "排名", width: "76px", render: (item) => <strong>#{item.rankNo}</strong> },
        {
            key: "user",
            label: "用户",
            width: "minmax(210px, .9fr)",
            render: (item) => (
                <div className={styles.dataUserIdentity}>
                    <Avatar alt="" src={item.user?.avatar || undefined}>
                        {(item.user?.username || String(item.userId || "-")).slice(0, 1)}
                    </Avatar>
                    <div className={styles.cellStack}>
                        <strong>{item.user?.username || `用户 #${item.userId || "-"}`}</strong>
                        <small>
                            {item.user?.displayUserId
                                ? `${item.user.displayUserId} · `
                                : `UID ${item.userId || "-"} · `}
                            {item.snapshot ? "结算快照" : "实时排名"}
                        </small>
                    </div>
                </div>
            ),
        },
        { key: "score", label: "积分", width: "120px", render: (item) => numeric(item.score) },
        { key: "coins", label: "金币", width: "120px", render: (item) => numeric(item.coinAmount) },
        { key: "gifts", label: "礼物数", width: "110px", render: (item) => numeric(item.giftCount) },
        {
            key: "first",
            label: "首次得分",
            width: "180px",
            render: (item) => formatMillis(item.firstScoredAtMs),
        },
    ];
    const pageCount = Math.max(1, Math.ceil(Number(data.total || 0) / Number(data.pageSize || 20)));

    return (
        <div className={styles.dataPanel}>
            <div className={styles.inlineFilters}>
                <TextField
                    label="榜单类型"
                    select
                    size="small"
                    value={boardType}
                    onChange={(event) => onBoardTypeChange(event.target.value)}
                >
                    <MenuItem value="daily">日榜</MenuItem>
                    <MenuItem value="total">总榜</MenuItem>
                </TextField>
                {boardType === "daily" ? (
                    <TextField
                        label="UTC 榜单日期"
                        select
                        size="small"
                        value={periodKey}
                        onChange={(event) => onPeriodChange(event.target.value)}
                    >
                        {periodOptions.map((item) => (
                            <MenuItem key={item} value={item}>
                                {item}
                            </MenuItem>
                        ))}
                    </TextField>
                ) : null}
                <PeriodStatus period={data.period} />
            </div>
            <DataState error={error} loading={loading} reportPageLoading={false} onRetry={onRetry}>
                <DataTable
                    columns={columns}
                    items={data.items || []}
                    minWidth="820px"
                    rowKey={(item) => `${item.rankNo}-${item.userId}`}
                    total={data.total || 0}
                />
                {pageCount > 1 ? (
                    <div className={styles.drawerPagination}>
                        <Pagination
                            count={pageCount}
                            page={page}
                            size="small"
                            onChange={(_, value) => onPageChange(value)}
                        />
                    </div>
                ) : null}
            </DataState>
        </div>
    );
}

function PeriodStatus({ period }) {
    if (!period?.periodKey) return null;
    return (
        <div className={styles.periodSummary}>
            <span className={`${styles.dataStatus} ${styles[`dataStatus_${period.status}`] || ""}`}>
                {periodStatusLabel(period.status)}
            </span>
            <span>{period.periodKey}</span>
            {period.settledAtMs ? (
                <small>结算 {formatMillis(period.settledAtMs)}</small>
            ) : period.settleAfterMs ? (
                <small>结算水位 {formatMillis(period.settleAfterMs)}</small>
            ) : null}
        </div>
    );
}

function numeric(value) {
    return <strong className={styles.numericCell}>{formatActivityMetric(value)}</strong>;
}

function periodStatusLabel(value) {
    if (value === "pending") return "计分中";
    if (value === "open") return "进行中";
    if (value === "settling") return "结算中";
    if (value === "settled") return "已结算";
    if (value === "cancelled") return "已取消";
    return value || "未知";
}
