import { useEffect, useMemo, useState } from "react";
import { formatMillis } from "@/shared/utils/time.js";
import styles from "@/features/app-users/app-users.module.css";

const roleLabels = {
    admin: "管理员",
    bd: "BD",
    bd_leader: "BD Leader",
    bdleader: "BD Leader",
    coin_seller: "币商",
    guild_leader: "公会长",
    host: "主播",
    manager: "经理",
    normal: "普通用户",
    ordinary: "普通用户",
};

export function GenderValue({ gender }) {
    return formatGender(gender);
}

export function GenderAgeTag({ age, gender }) {
    const normalizedGender = normalizeGender(gender);
    const normalizedAge = Number(age);
    const ageLabel = Number.isFinite(normalizedAge) && normalizedAge >= 0 ? normalizedAge : "-";

    // 未设置或无法识别的性别不伪造颜色语义，仍保留年龄，避免列表信息因字段迁移缺失而消失。
    if (!normalizedGender) {
        return <span className={styles.genderAgeUnknown}>年龄 {ageLabel}</span>;
    }

    return (
        <span
            aria-label={`${normalizedGender === "female" ? "女" : "男"}，${ageLabel} 岁`}
            className={normalizedGender === "female" ? styles.genderAgeFemale : styles.genderAgeMale}
        >
            {normalizedGender === "female" ? "♀" : "♂"} {ageLabel}
        </span>
    );
}

export function UserLevelsValue({ levels }) {
    const entries = [
        ["财富", levels?.wealth],
        ["魅力", levels?.charm],
        ["游戏", levels?.game],
    ];
    return (
        <div className={styles.userLevels}>
            {entries.map(([label, level]) => (
                <span className={styles.userLevel} key={label}>
                    <span>{label}</span>
                    <strong>{level ? `Lv${numericLevel(level.displayLevel ?? level.realLevel)}` : "-"}</strong>
                </span>
            ))}
        </div>
    );
}

export function LevelValue({ level, showReal = false }) {
    if (!level) {
        return "-";
    }
    const displayLevel = numericLevel(level.displayLevel ?? level.realLevel);
    const realLevel = numericLevel(level.realLevel);
    const temporary = Number(level.expiresAtMs || 0) > 0 && Number(level.temporaryTargetLevel || 0) > 0;
    return (
        <div className={styles.stack}>
            <span className={styles.levelPrimary}>Lv{displayLevel}</span>
            {showReal || temporary ? (
                <span className={styles.meta}>
                    {showReal ? `真实 Lv${realLevel}` : ""}
                    {showReal && temporary ? " · " : ""}
                    {temporary ? `临时至 ${formatMillis(level.expiresAtMs)}` : ""}
                </span>
            ) : null}
        </div>
    );
}

export function RolesValue({ roles }) {
    const labels = normalizeRoles(roles);
    return <span className={styles.rolesValue}>{labels.join("、")}</span>;
}

export function OperatorValue({ operatedAtMs, operator }) {
    if (!operator?.name && !operator?.adminId && !operatedAtMs) {
        return "-";
    }
    const name = operator?.name || (operator?.adminId ? `管理员 ${operator.adminId}` : "-");
    return (
        <div className={styles.stack}>
            <span>{name}</span>
            <span className={styles.meta}>
                {[operator?.action, formatMillis(operatedAtMs)].filter((value) => value && value !== "-").join(" · ") || "-"}
            </span>
        </div>
    );
}

export function BanCountdown({ ban, status }) {
    const [now, setNow] = useState(0);
    const banned = status === "banned" || status === "disabled" || Boolean(ban?.active);
    const expiresAtMs = Number(ban?.expiresAtMs || 0);

    useEffect(() => {
        if (!banned || ban?.permanent || expiresAtMs <= 0) {
            return undefined;
        }
        const startupTimer = window.setTimeout(() => setNow(Date.now()), 0);
        const timer = window.setInterval(() => setNow(Date.now()), 1000);
        return () => {
            window.clearTimeout(startupTimer);
            window.clearInterval(timer);
        };
    }, [ban?.permanent, banned, expiresAtMs]);

    const label = useMemo(() => {
        if (!banned) {
            return "-";
        }
        // 兼容迁移前只有 banned/disabled 状态、没有事实记录的用户：按永久展示，绝不因缺失到期时间误判为可自动解封。
        if (ban?.permanent || expiresAtMs <= 0) {
            return "永久";
        }
        if (now <= 0) {
            return `至 ${formatMillis(expiresAtMs)}`;
        }
        const remainingMs = expiresAtMs - now;
        if (remainingMs <= 0) {
            return "等待自动解封";
        }
        return formatDuration(remainingMs);
    }, [ban?.permanent, banned, expiresAtMs, now]);

    return <span className={banned ? styles.banCountdown : styles.meta}>{label}</span>;
}

export function formatGender(gender) {
    const value = String(gender || "").toLowerCase();
    if (value === "male" || value === "m" || value === "男") {
        return "男";
    }
    if (value === "female" || value === "f" || value === "女") {
        return "女";
    }
    if (value === "non_binary") {
        return "非二元";
    }
    return gender || "-";
}

function normalizeGender(gender) {
    const value = String(gender || "").toLowerCase();
    if (value === "female" || value === "f" || value === "女") {
        return "female";
    }
    if (value === "male" || value === "m" || value === "男") {
        return "male";
    }
    return "";
}

export function formatUsdMinor(value) {
    const amount = Number(value);
    if (!Number.isFinite(amount)) {
        return "-";
    }
    return new Intl.NumberFormat("zh-CN", { currency: "USD", style: "currency" }).format(amount / 100);
}

export function normalizeRoles(roles) {
    const values = Array.isArray(roles) ? roles.filter(Boolean) : [];
    if (!values.length) {
        return ["普通用户"];
    }
    return Array.from(new Set(values.map((role) => roleLabels[String(role).toLowerCase()] || String(role))));
}

function numericLevel(value) {
    const level = Number(value || 0);
    return Number.isFinite(level) ? Math.max(0, Math.trunc(level)) : 0;
}

function formatDuration(milliseconds) {
    const totalSeconds = Math.max(0, Math.ceil(milliseconds / 1000));
    const days = Math.floor(totalSeconds / 86400);
    const hours = Math.floor((totalSeconds % 86400) / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    if (days > 0) {
        return `${days}天 ${hours}小时`;
    }
    if (hours > 0) {
        return `${hours}小时 ${minutes}分`;
    }
    if (minutes > 0) {
        return `${minutes}分 ${seconds}秒`;
    }
    return `${seconds}秒`;
}
