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 { formatMillis } from "@/shared/utils/time.js";
import styles from "@/features/activity-templates/activity-templates.module.css";

const claimStatusOptions = [
    ["", "全部状态"],
    ["pending", "待发放"],
    ["running", "发放中"],
    ["granted", "已发放"],
    ["failed", "失败"],
];

export function ActivityTemplateTaskClaimsPanel({
    abilities,
    data,
    error,
    loading,
    loadingAction,
    onDayChange,
    onPageChange,
    onRetry,
    onRetryClaim,
    onStatusChange,
    onTaskKeyChange,
    onUserIdChange,
    page,
    periodOptions,
    status,
    taskDay,
    taskKey,
    taskOptions,
    userId,
}) {
    const columns = [
        {
            key: "claim",
            label: "领奖记录 / 任务",
            width: "minmax(230px, 1fr)",
            render: (item) => (
                <div className={styles.cellStack} title={item.claimId}>
                    <strong>{item.claimId || "-"}</strong>
                    <small>
                        v{item.versionNo} · {item.taskDay} · {item.taskKey}
                    </small>
                </div>
            ),
        },
        {
            key: "user",
            label: "用户 / 归属区域",
            width: "190px",
            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.earningRegionId || "-"}
                        </small>
                    </div>
                </div>
            ),
        },
        {
            key: "reward",
            label: "发布态奖励",
            width: "minmax(190px, .85fr)",
            render: (item) => (
                <div className={styles.cellStack} title={item.rewardSnapshotHash || ""}>
                    <strong>{item.rewardName || `资源组 #${item.rewardResourceGroupId || "-"}`}</strong>
                    <small>
                        {item.rewardItems.length} 项 · {item.rewardSnapshotId || `group ${item.rewardResourceGroupId || "-"}`}
                    </small>
                </div>
            ),
        },
        {
            key: "status",
            label: "状态 / 尝试",
            width: "124px",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span className={`${styles.dataStatus} ${styles[`dataStatus_${item.status}`] || ""}`}>
                        {claimStatusLabel(item.status)}
                    </span>
                    <small>{item.attemptCount || 0} 次</small>
                </div>
            ),
        },
        {
            key: "grant",
            label: "钱包发放",
            width: "minmax(160px, .7fr)",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>{item.walletGrantId || "-"}</span>
                    <small>{item.grantedAtMs ? formatMillis(item.grantedAtMs) : "尚未发放"}</small>
                </div>
            ),
        },
        {
            key: "attribution",
            label: "业务归因 / 更新",
            width: "190px",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>{formatMillis(item.attributionAtMs)}</span>
                    <small>更新 {formatMillis(item.updatedAtMs || item.createdAtMs)}</small>
                </div>
            ),
        },
        {
            key: "failure",
            label: "失败原因",
            width: "minmax(190px, .8fr)",
            render: (item) => (
                <span className={styles.ellipsisCell} title={item.failureReason || ""}>
                    {item.failureReason || "-"}
                </span>
            ),
        },
        {
            key: "actions",
            label: "操作",
            width: "72px",
            render: (item) => (
                <AdminRowActions>
                    {abilities.canRetry && item.status === "failed" ? (
                        <AdminActionIconButton
                            disabled={loadingAction === `retry-claim:${item.claimId}`}
                            label="重试发放"
                            onClick={() => onRetryClaim(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="UTC 任务日"
                    select
                    size="small"
                    value={taskDay}
                    onChange={(event) => onDayChange(event.target.value)}
                >
                    <MenuItem value="">全部日期</MenuItem>
                    {periodOptions.map((item) => (
                        <MenuItem key={item} value={item}>
                            {item}
                        </MenuItem>
                    ))}
                </TextField>
                <TextField
                    label="任务"
                    select
                    size="small"
                    value={taskKey}
                    onChange={(event) => onTaskKeyChange(event.target.value)}
                >
                    <MenuItem value="">全部任务</MenuItem>
                    {taskOptions.map((item) => (
                        <MenuItem key={item.taskKey} value={item.taskKey}>
                            {item.taskKey}
                        </MenuItem>
                    ))}
                </TextField>
                <TextField
                    label="用户 ID"
                    placeholder="精确查询"
                    size="small"
                    value={userId}
                    onChange={(event) => onUserIdChange(event.target.value)}
                />
                <StatusSelect label="发放状态" options={claimStatusOptions} value={status} onChange={onStatusChange} />
            </div>
            <DataState error={error} loading={loading} reportPageLoading={false} onRetry={onRetry}>
                <DataTable
                    columns={columns}
                    items={data.items || []}
                    minWidth="1510px"
                    rowKey={(item) => item.claimId}
                    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 claimStatusLabel(value) {
    return claimStatusOptions.find(([status]) => status === value)?.[1] || value || "未知";
}
