import { ASSET_SLOTS, DEFAULT_DISPLAY_CONFIG } from "@/features/activity-templates/constants.js";

export function createEmptyActivityTemplateForm(appCode = "") {
    return {
        activityType: "gift_challenge",
        allRegions: false,
        appCode,
        assets: ASSET_SLOTS.map((slot) => ({ ...slot, mediaType: "image", url: "" })),
        dailyLeaderboardSize: "100",
        dailyRankRewards: defaultDailyRankRewards(),
        displayConfigJson: JSON.stringify(DEFAULT_DISPLAY_CONFIG, null, 2),
        gifts: [],
        name: "",
        lifecycleStatus: "draft",
        publishedVersion: 0,
        regionIds: [],
        revision: 0,
        rulesAr: "",
        rulesEn: "",
        status: "draft",
        tasks: [createActivityTask("daily_visit", 0)],
        templateCode: "",
        templateId: "",
        timeRange: { endMs: "", startMs: "" },
        titleAr: "",
        titleEn: "",
        totalLeaderboardSize: "100",
        totalRankRewards: defaultTotalRankRewards(),
    };
}

export function activityTemplateFormFromDto(template, appCode = "") {
    const english = (template?.locales || []).find((locale) => locale.locale === "en") || {};
    const arabic = (template?.locales || []).find((locale) => locale.locale === "ar") || {};
    const rankRewards = template?.rankRewards || [];
    const assets = ASSET_SLOTS.map((slot) => {
        const asset = (template?.assets || []).find(
            (item) => item.assetKey === slot.assetKey && item.locale === slot.locale,
        );
        return {
            ...slot,
            mediaType: asset?.mediaType || "image",
            url: asset?.url || "",
        };
    });
    const extraAssets = (template?.assets || [])
        .filter((item) => !ASSET_SLOTS.some((slot) => slot.assetKey === item.assetKey && slot.locale === item.locale))
        .map((item) => ({
            assetKey: item.assetKey,
            label: `${item.assetKey} · ${item.locale}`,
            locale: item.locale,
            mediaType: item.mediaType || "image",
            url: item.url,
        }));

    return {
        activityType: template?.activityType || "gift_challenge",
        allRegions: Boolean(template?.allRegions),
        appCode: template?.appCode || appCode,
        assets: [...assets, ...extraAssets],
        dailyLeaderboardSize: String(template?.dailyLeaderboardSize || 100),
        dailyRankRewards: rewardsForBoard(rankRewards, "daily", defaultDailyRankRewards()),
        displayConfigJson: prettyJson(template?.displayConfigJson),
        gifts: (template?.gifts || []).map((gift) => ({
            coinPrice: String(gift.coinPrice || ""),
            giftId: String(gift.giftId || ""),
            iconUrl: gift.iconUrl || "",
            name: gift.name || "",
            priceVersion: gift.priceVersion || "",
        })),
        name: template?.name || "",
        lifecycleStatus: template?.lifecycleStatus || template?.status || "draft",
        publishedVersion: Number(template?.publishedVersion || 0),
        regionIds: (template?.regionIds || []).map(String),
        revision: Number(template?.revision || 0),
        rulesAr: arabic.rules || "",
        rulesEn: english.rules || "",
        status: template?.status || "draft",
        tasks: (template?.tasks || []).map((task) => ({
            rewardResourceGroupId: task.rewardResourceGroupId ? String(task.rewardResourceGroupId) : "",
            targetValue: String(task.targetValue || ""),
            taskKey: task.taskKey || "",
            taskType: task.taskType || "daily_visit",
        })),
        templateCode: template?.templateCode || "",
        templateId: template?.templateId || "",
        timeRange: {
            endMs: template?.endMs || "",
            startMs: template?.startMs || "",
        },
        titleAr: arabic.title || "",
        titleEn: english.title || "",
        totalLeaderboardSize: String(template?.totalLeaderboardSize || 100),
        totalRankRewards: rewardsForBoard(rankRewards, "total", defaultTotalRankRewards()),
    };
}

export function activityTemplatePayloadFromForm(form) {
    return {
        activity_type: "gift_challenge",
        all_regions: Boolean(form.allRegions),
        assets: (form.assets || [])
            .filter((asset) => asset.url)
            .map((asset, index) => ({
                asset_key: asset.assetKey,
                locale: asset.locale || "*",
                media_type: asset.mediaType || mediaTypeFromURL(asset.url),
                sort_order: index + 1,
                url: asset.url,
            })),
        daily_leaderboard_size: Number(form.dailyLeaderboardSize),
        display_config_json: compactJson(form.displayConfigJson),
        end_ms: Number(form.timeRange.endMs || 0),
        gifts: (form.gifts || []).map((gift, index) => ({
            coin_price: Number(gift.coinPrice || 0),
            gift_id: String(gift.giftId),
            icon_url: gift.iconUrl || "",
            name: gift.name || "",
            price_version: gift.priceVersion || "",
            sort_order: index + 1,
        })),
        locales: [
            { locale: "en", rules: form.rulesEn.trim(), title: form.titleEn.trim() },
            { locale: "ar", rules: form.rulesAr.trim(), title: form.titleAr.trim() },
        ].filter((locale) => locale.locale === "en" || locale.rules || locale.title),
        name: form.name.trim(),
        rank_rewards: [
            ...rankRewardPayloads(form.dailyRankRewards, "daily"),
            ...rankRewardPayloads(form.totalRankRewards, "total"),
        ],
        region_ids: form.allRegions ? [] : (form.regionIds || []).map(Number),
        start_ms: Number(form.timeRange.startMs || 0),
        tasks: (form.tasks || []).map((task, index) => ({
            reward_resource_group_id: Number(task.rewardResourceGroupId || 0),
            sort_order: index + 1,
            target_value: Number(task.targetValue || 0),
            task_key: task.taskKey.trim(),
            task_type: task.taskType,
        })),
        template_code: form.templateCode.trim().toLowerCase(),
        total_leaderboard_size: Number(form.totalLeaderboardSize),
    };
}

export function giftFormValue(gift) {
    const resource = gift?.resource || {};
    return {
        coinPrice: String(gift?.coinPrice ?? gift?.giftPriceCoin ?? resource.coinPrice ?? ""),
        giftId: String(gift?.giftId || ""),
        iconUrl: resource.previewUrl || resource.assetUrl || gift?.giftIconUrl || "",
        name: gift?.name || gift?.giftName || resource.name || "",
        priceVersion: gift?.priceVersion || String(gift?.updatedAtMs || resource.updatedAtMs || "v1"),
    };
}

export function giftDtoFromForm(gift) {
    return {
        coinPrice: Number(gift?.coinPrice || 0),
        giftId: String(gift?.giftId || ""),
        name: gift?.name || "",
        priceVersion: gift?.priceVersion || "",
        resource: {
            assetUrl: gift?.iconUrl || "",
            coinPrice: Number(gift?.coinPrice || 0),
            name: gift?.name || "",
            previewUrl: gift?.iconUrl || "",
        },
    };
}

export function createActivityTask(taskType = "gift_count", index = 0) {
    return {
        rewardResourceGroupId: "",
        targetValue: taskType === "daily_visit" ? "1" : "1",
        taskKey: `${taskType}_${index + 1}`,
        taskType,
    };
}

export function createNextActivityTask(tasks, taskType = "gift_count") {
    const usedKeys = new Set((tasks || []).map((task) => String(task.taskKey || "").trim()));
    let sequence = 1;
    while (usedKeys.has(`${taskType}_${sequence}`)) {
        sequence += 1;
    }
    return createActivityTask(taskType, sequence - 1);
}

export function createRankReward(rankFrom = 1, rankTo = rankFrom) {
    return { rankFrom: String(rankFrom), rankTo: String(rankTo), resourceGroupId: "" };
}

export function mediaTypeFromURL(value) {
    const url = String(value || "")
        .toLowerCase()
        .split(/[?#]/)[0];
    if (url.endsWith(".svga")) return "svga";
    if (url.endsWith(".pag")) return "pag";
    if (url.endsWith(".webp")) return "webp";
    return "image";
}

export function parseDisplayConfig(value) {
    try {
        const parsed = JSON.parse(value || "{}");
        return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : DEFAULT_DISPLAY_CONFIG;
    } catch {
        return DEFAULT_DISPLAY_CONFIG;
    }
}

function rewardsForBoard(rewards, boardType, fallback) {
    const items = rewards
        .filter((reward) => reward.boardType === boardType)
        .sort((left, right) => left.rankFrom - right.rankFrom)
        .map((reward) => ({
            rankFrom: String(reward.rankFrom),
            rankTo: String(reward.rankTo),
            resourceGroupId: reward.resourceGroupId ? String(reward.resourceGroupId) : "",
        }));
    return items.length ? items : fallback;
}

function rankRewardPayloads(rewards, boardType) {
    return (rewards || []).map((reward, index) => ({
        board_type: boardType,
        rank_from: Number(reward.rankFrom),
        rank_to: Number(reward.rankTo),
        resource_group_id: Number(reward.resourceGroupId || 0),
        sort_order: index + 1,
    }));
}

function defaultDailyRankRewards() {
    return [createRankReward(1), createRankReward(2), createRankReward(3)];
}

function defaultTotalRankRewards() {
    return [
        createRankReward(1),
        createRankReward(2),
        createRankReward(3),
        createRankReward(4, 6),
        createRankReward(7, 10),
    ];
}

function prettyJson(value) {
    try {
        return JSON.stringify(JSON.parse(value || "{}"), null, 2);
    } catch {
        return value || "{}";
    }
}

function compactJson(value) {
    const parsed = JSON.parse(value || "{}");
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
        throw new Error("展示配置必须是 JSON 对象");
    }
    return JSON.stringify(parsed);
}
