import CardGiftcardOutlined from "@mui/icons-material/CardGiftcardOutlined";
import EmojiEventsOutlined from "@mui/icons-material/EmojiEventsOutlined";
import TaskAltOutlined from "@mui/icons-material/TaskAltOutlined";
import { useEffect, useMemo, useState } from "react";
import styles from "@/features/activity-templates/activity-templates.module.css";
import { parseDisplayConfig } from "@/features/activity-templates/model.js";

export function ActivityPhonePreview({ form, resourceGroups = [] }) {
    const [locale, setLocale] = useState("en");
    const config = useMemo(() => parseDisplayConfig(form.displayConfigJson), [form.displayConfigJson]);
    const [tab, setTab] = useState(() => (config.default_tab === "leaderboard" ? "leaderboard" : "tasks"));
    const configuredDefaultTab = config.default_tab === "leaderboard" ? "leaderboard" : "tasks";

    useEffect(() => {
        setTab(configuredDefaultTab);
    }, [configuredDefaultTab]);

    const rtl = locale === "ar";
    const title = locale === "ar" ? form.titleAr || form.titleEn : form.titleEn;
    const hero = findAsset(form.assets, "hero", locale) || findAsset(form.assets, "hero", "en");
    const pageBackground = findAsset(form.assets, "page_background", "*");
    const groupsById = new Map(resourceGroups.map((group) => [String(group.groupId), group]));

    return (
        <aside className={styles.previewPanel}>
            <div className={styles.previewToolbar}>
                <span>手机预览</span>
                <div className={styles.previewLocale}>
                    <button
                        className={locale === "en" ? styles.previewLocaleActive : ""}
                        type="button"
                        onClick={() => setLocale("en")}
                    >
                        EN
                    </button>
                    <button
                        className={locale === "ar" ? styles.previewLocaleActive : ""}
                        type="button"
                        onClick={() => setLocale("ar")}
                    >
                        AR
                    </button>
                </div>
            </div>
            <div className={styles.phoneFrame}>
                <div
                    className={styles.phoneScreen}
                    dir={rtl ? "rtl" : "ltr"}
                    style={pageBackground ? { backgroundImage: `url(${pageBackground})` } : undefined}
                >
                    <div className={styles.phoneHero} style={hero ? { backgroundImage: `url(${hero})` } : undefined}>
                        <span className={styles.phoneBack}>‹</span>
                        <strong>{title || "Gift Challenge"}</strong>
                    </div>
                    <div className={styles.phoneCountdown}>
                        {["29D", "23H", "12M", "45S"].map((part) => (
                            <span key={part}>{part}</span>
                        ))}
                    </div>
                    <section className={styles.phoneGiftPanel}>
                        <span className={styles.phoneSectionTitle}>{rtl ? "هدايا النشاط" : "Activity gifts"}</span>
                        <div className={styles.phoneGiftRail}>
                            {(form.gifts || []).slice(0, 5).map((gift) => (
                                <div className={styles.phoneGift} key={gift.giftId}>
                                    {gift.iconUrl ? (
                                        <img alt="" src={gift.iconUrl} />
                                    ) : (
                                        <CardGiftcardOutlined fontSize="small" />
                                    )}
                                    <small>{Number(gift.coinPrice || 0).toLocaleString("en-US")}</small>
                                </div>
                            ))}
                            {!form.gifts?.length ? (
                                <div className={styles.phoneGiftEmpty}>
                                    <CardGiftcardOutlined fontSize="small" />
                                </div>
                            ) : null}
                        </div>
                    </section>
                    <div className={styles.phoneTabs}>
                        <button
                            aria-pressed={tab === "tasks"}
                            className={tab === "tasks" ? styles.phoneTabActive : ""}
                            type="button"
                            onClick={() => setTab("tasks")}
                        >
                            <TaskAltOutlined fontSize="inherit" />
                            {rtl ? "المهام" : "Tasks"}
                        </button>
                        <button
                            aria-pressed={tab === "leaderboard"}
                            className={tab === "leaderboard" ? styles.phoneTabActive : ""}
                            type="button"
                            onClick={() => setTab("leaderboard")}
                        >
                            <EmojiEventsOutlined fontSize="inherit" />
                            {rtl ? "التصنيف" : "Ranking"}
                        </button>
                    </div>
                    {tab === "tasks" ? (
                        <div className={styles.phoneTaskList}>
                            {(form.tasks || []).slice(0, 4).map((task) => (
                                <div className={styles.phoneTask} key={task.taskKey}>
                                    <span>
                                        <strong>{taskLabel(task, rtl)}</strong>
                                        <small>
                                            {groupName(groupsById.get(String(task.rewardResourceGroupId)), rtl)}
                                        </small>
                                    </span>
                                    <button type="button">{rtl ? "استلام" : "Claim"}</button>
                                </div>
                            ))}
                            {!form.tasks?.length ? <div className={styles.phoneEmpty}>No tasks</div> : null}
                        </div>
                    ) : (
                        <div className={styles.phoneRanking}>
                            <div className={styles.phonePodium}>
                                {[2, 1, 3].map((rank) => (
                                    <span className={rank === 1 ? styles.phonePodiumFirst : ""} key={rank}>
                                        <i>{rank}</i>
                                        <small>TOP {rank}</small>
                                    </span>
                                ))}
                            </div>
                            {[4, 5, 6].map((rank) => (
                                <div className={styles.phoneRankRow} key={rank}>
                                    <span>{rank}</span>
                                    <i />
                                    <strong>User {rank}</strong>
                                    <small>15,000</small>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </aside>
    );
}

function findAsset(assets, assetKey, locale) {
    return (assets || []).find((asset) => asset.assetKey === assetKey && asset.locale === locale)?.url || "";
}

function groupName(group, rtl) {
    if (!group) return rtl ? "مكافأة" : "Reward";
    return group.name || group.groupCode || `#${group.groupId}`;
}

function taskLabel(task, rtl) {
    if (rtl) {
        if (task.taskType === "daily_visit") return "زيارة صفحة النشاط";
        if (task.taskType === "gift_coin_amount") return `إرسال هدايا بقيمة ${task.targetValue}`;
        return `إرسال ${task.targetValue} هدية`;
    }
    if (task.taskType === "daily_visit") return "Visit activity page";
    if (task.taskType === "gift_coin_amount") return `Send ${task.targetValue} coins`;
    return `Send ${task.targetValue} gifts`;
}
