import ReplayOutlined from "@mui/icons-material/ReplayOutlined";
import Avatar from "@mui/material/Avatar";
import MenuItem from "@mui/material/MenuItem";
import Pagination from "@mui/material/Pagination";
import TextField from "@mui/material/TextField";
import { AdminActionIconButton, AdminRowActions } from "@/shared/ui/AdminListLayout.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { StatusSelect } from "@/shared/ui/StatusSelect.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";

const rewardStatusOptions = [
    ["", "全部状态"],
    ["pending", "待发放"],
    ["running", "发放中"],
    ["granted", "已发放"],
    ["failed", "失败"],
    ["dead", "人工处理"],
];

export function ActivityTemplateRewardsPanel({
    abilities,
    boardType,
    data,
    error,
    loading,
    loadingAction,
    onBoardTypeChange,
    onPageChange,
    onPeriodChange,
    onRetry,
    onRetryJob,
    onStatusChange,
    page,
    periodKey,
    periodOptions,
    status,
}) {
    const columns = [
        {
            key: "job",
            label: "奖励任务",
            width: "minmax(210px, 1fr)",
            render: (item) => (
                <div className={styles.cellStack} title={item.rewardJobId}>
                    <strong>{item.rewardJobId || "-"}</strong>
                    <small>
                        v{item.versionNo} · {item.boardType === "daily" ? "日榜" : "总榜"} {item.periodKey}
                    </small>
                </div>
            ),
        },
        {
            key: "user",
            label: "用户 / 名次",
            width: "150px",
            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 || `UID ${item.userId || "-"}`} · 排名 #{item.rankNo} ·{" "}
                            {formatActivityMetric(item.score)} 分
                        </small>
                    </div>
                </div>
            ),
        },
        {
            key: "resource",
            label: "发布态奖励",
            width: "minmax(180px, .75fr)",
            render: (item) => (
                <div className={styles.cellStack} title={item.rewardSnapshotHash || ""}>
                    <strong>{item.rewardName || `资源组 #${item.resourceGroupId || "-"}`}</strong>
                    <small>
                        {item.rewardItems.length} 项 · {item.rewardSnapshotId || `group ${item.resourceGroupId || "-"}`}
                    </small>
                </div>
            ),
        },
        {
            key: "status",
            label: "状态 / 尝试",
            width: "130px",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span className={`${styles.dataStatus} ${styles[`dataStatus_${item.status}`] || ""}`}>
                        {rewardStatusLabel(item.status)}
                    </span>
                    <small>
                        {item.attemptCount || 0}/{item.maxAttempts || "-"} 次
                        {item.nextRetryAtMs > 0 ? ` · 下次 ${formatMillis(item.nextRetryAtMs)}` : ""}
                    </small>
                </div>
            ),
        },
        {
            key: "failure",
            label: "失败原因",
            width: "minmax(200px, .9fr)",
            render: (item) => (
                <span className={styles.ellipsisCell} title={item.failureReason || ""}>
                    {item.failureReason || "-"}
                </span>
            ),
        },
        {
            key: "time",
            label: "更新时间",
            width: "180px",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>{formatMillis(item.updatedAtMs)}</span>
                    <small>
                        {item.grantedAtMs
                            ? `发放 ${formatMillis(item.grantedAtMs)}`
                            : `创建 ${formatMillis(item.createdAtMs)}`}
                    </small>
                </div>
            ),
        },
        {
            key: "actions",
            label: "操作",
            width: "72px",
            render: (item) => (
                <AdminRowActions>
                    {abilities.canRetry && ["failed", "dead"].includes(item.status) ? (
                        <AdminActionIconButton
                            disabled={loadingAction === `retry:${item.rewardJobId}`}
                            label="重试发放"
                            onClick={() => onRetryJob(item)}
                        >
                            <ReplayOutlined fontSize="small" />
                        </AdminActionIconButton>
                    ) : null}
                </AdminRowActions>
            ),
        },
    ];
    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="">全部榜单</MenuItem>
                    <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)}
                    >
                        <MenuItem value="">全部周期</MenuItem>
                        {periodOptions.map((item) => (
                            <MenuItem key={item} value={item}>
                                {item}
                            </MenuItem>
                        ))}
                    </TextField>
                ) : null}
                <StatusSelect label="发放状态" options={rewardStatusOptions} value={status} onChange={onStatusChange} />
            </div>
            <DataState error={error} loading={loading} reportPageLoading={false} onRetry={onRetry}>
                <DataTable
                    columns={columns}
                    items={data.items || []}
                    minWidth="1260px"
                    rowKey={(item) => item.rewardJobId}
                    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 rewardStatusLabel(value) {
    return rewardStatusOptions.find(([status]) => status === value)?.[1] || value || "未知";
}
