import { MultiSeriesLineChart } from "@/shared/charts/MultiSeriesLineChart.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { formatActivityMetric } from "@/features/activity-templates/dataModel.js";
import styles from "@/features/activity-templates/activity-templates.module.css";

const metricDefinitions = [
    ["participants", "参与用户", "人"],
    ["visitCount", "访问人次", "次"],
    ["giftUsers", "送礼用户", "人"],
    ["taskUsers", "任务用户", "人"],
    ["coinAmount", "活动金币", "coin"],
    ["giftEventCount", "送礼事件", "次"],
    ["giftCount", "礼物数量", "个"],
    ["taskProgress", "任务进度", "点"],
    ["taskCompleted", "任务完成", "次"],
    ["taskClaimed", "任务领奖", "次"],
];

export function ActivityTemplateDataOverview({ data, error, loading, onRetry, template }) {
    const giftLabels = new Map((template.gifts || []).map((gift) => [String(gift.giftId), gift]));
    const taskLabels = new Map((template.tasks || []).map((task) => [String(task.taskKey), task]));
    const giftColumns = [
        {
            key: "gift",
            label: "礼物",
            width: "minmax(180px, 1fr)",
            render: (item) => {
                const gift = giftLabels.get(String(item.giftId));
                return (
                    <div className={styles.cellStack}>
                        <strong>{gift?.name || item.giftId || "-"}</strong>
                        <small>{item.giftId || "-"}</small>
                    </div>
                );
            },
        },
        { key: "users", label: "送礼用户", width: "100px", render: (item) => metric(item.giftUsers) },
        { key: "events", label: "事件", width: "90px", render: (item) => metric(item.giftEventCount) },
        { key: "count", label: "数量", width: "90px", render: (item) => metric(item.giftCount) },
        { key: "coins", label: "金币", width: "110px", render: (item) => metric(item.coinAmount) },
    ];
    const taskColumns = [
        {
            key: "task",
            label: "任务",
            width: "minmax(200px, 1fr)",
            render: (item) => {
                const task = taskLabels.get(String(item.taskKey));
                return (
                    <div className={styles.cellStack}>
                        <strong>{item.taskKey || "-"}</strong>
                        <small>{taskTypeLabel(task?.taskType || item.taskType)}</small>
                    </div>
                );
            },
        },
        { key: "users", label: "任务用户", width: "100px", render: (item) => metric(item.taskUsers) },
        { key: "progress", label: "累计进度", width: "100px", render: (item) => metric(item.taskProgress) },
        { key: "completed", label: "完成", width: "90px", render: (item) => metric(item.taskCompleted) },
        { key: "claimed", label: "领奖", width: "90px", render: (item) => metric(item.taskClaimed) },
    ];
    const trendSeries = [
        { data: data.trend.map((item) => item.participants), key: "participants", name: "参与用户" },
        {
            data: data.trend.map((item) => item.visitCount),
            key: "visits",
            name: "访问人次",
            colorToken: "--chart-violet",
        },
        {
            data: data.trend.map((item) => item.giftUsers),
            key: "gift-users",
            name: "送礼用户",
            colorToken: "--chart-green",
        },
        {
            data: data.trend.map((item) => item.taskUsers),
            key: "task-users",
            name: "任务用户",
            colorToken: "--chart-orange",
        },
        {
            data: data.trend.map((item) => item.coinAmount),
            key: "coins",
            name: "金币",
            colorToken: "--chart-red",
            yAxisIndex: 1,
        },
    ];

    return (
        <DataState error={error} loading={loading} reportPageLoading={false} onRetry={onRetry}>
            <div className={styles.dataOverview}>
                <div className={styles.metricGrid}>
                    {metricDefinitions.map(([key, label, unit]) => (
                        <div className={styles.metricItem} key={key}>
                            <span>{label}</span>
                            <strong>{formatActivityMetric(data.overview[key])}</strong>
                            <small>{unit}</small>
                        </div>
                    ))}
                </div>
                <section className={styles.dataSection}>
                    <div className={styles.dataSectionHeader}>
                        <div>
                            <h3>每日趋势</h3>
                            <span>{effectiveWindowLabel(data)}</span>
                        </div>
                        <span className={styles.dataMetaBadge}>{data.timezone || "UTC"} · 日粒度</span>
                    </div>
                    <MultiSeriesLineChart
                        ariaLabel="活动模版每日趋势"
                        categories={data.trend.map((item) => item.statDay)}
                        series={trendSeries}
                    />
                </section>
                <div className={styles.dataRankingGrid}>
                    <section className={styles.dataSection}>
                        <div className={styles.dataSectionHeader}>
                            <div>
                                <h3>礼物排行</h3>
                                <span>按金币、数量降序</span>
                            </div>
                            <span>
                                {data.gifts.length} / {data.dimensionLimit || 100}
                            </span>
                        </div>
                        <DataTable
                            columns={giftColumns}
                            items={data.gifts}
                            minWidth="590px"
                            rowKey={(item) => item.giftId}
                            total={data.gifts.length}
                        />
                    </section>
                    <section className={styles.dataSection}>
                        <div className={styles.dataSectionHeader}>
                            <div>
                                <h3>任务排行</h3>
                                <span>按完成、领奖降序</span>
                            </div>
                            <span>
                                {data.tasks.length} / {data.dimensionLimit || 100}
                            </span>
                        </div>
                        <DataTable
                            columns={taskColumns}
                            items={data.tasks}
                            minWidth="620px"
                            rowKey={(item) => item.taskKey}
                            total={data.tasks.length}
                        />
                    </section>
                </div>
            </div>
        </DataState>
    );
}

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

function effectiveWindowLabel(data) {
    if (!data.startMs || !data.endMs) return "UTC 统计窗口";
    return `${new Date(data.startMs).toISOString().slice(0, 10)} 至 ${new Date(data.endMs - 1).toISOString().slice(0, 10)}`;
}

function taskTypeLabel(value) {
    if (value === "daily_visit") return "每日访问";
    if (value === "gift_count") return "礼物数量";
    if (value === "gift_coin_amount") return "礼物金币";
    return value || "-";
}
