import { useCallback, useMemo, useRef, useState } from "react";
import { AdminPrettyDisplayID, AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import { getAppUser } from "@/features/app-users/api";
import { appUserStatusLabels } from "@/features/app-users/constants.js";
import { AppUserDetailContext } from "@/features/app-users/components/AppUserDetailContext.jsx";
import styles from "@/features/app-users/app-users.module.css";

export function AppUserDetailProvider({ children }) {
    const { showToast } = useToast();
    const requestSeqRef = useRef(0);
    const [detailUser, setDetailUser] = useState(null);
    const [loadingUserId, setLoadingUserId] = useState("");

    const closeAppUserDetail = useCallback(() => {
        requestSeqRef.current += 1;
        setDetailUser(null);
        setLoadingUserId("");
    }, []);

    const openAppUserDetail = useCallback(
        async (source) => {
            const seedUser = normalizeDetailSeed(source);
            if (!seedUser.userId) {
                showToast("缺少用户 ID，无法打开用户详情", "error");
                return;
            }

            const requestSeq = requestSeqRef.current + 1;
            requestSeqRef.current = requestSeq;
            setDetailUser(seedUser);
            setLoadingUserId(seedUser.userId);

            try {
                const latestUser = await getAppUser(seedUser.userId);
                if (requestSeqRef.current === requestSeq) {
                    setDetailUser({ ...seedUser, ...latestUser });
                }
            } catch (err) {
                if (requestSeqRef.current === requestSeq) {
                    showToast(err.message || "加载用户详情失败", "error");
                }
            } finally {
                if (requestSeqRef.current === requestSeq) {
                    setLoadingUserId("");
                }
            }
        },
        [showToast],
    );

    const value = useMemo(() => ({ closeAppUserDetail, openAppUserDetail }), [closeAppUserDetail, openAppUserDetail]);

    return (
        <AppUserDetailContext.Provider value={value}>
            {children}
            <AppUserDetailDrawer
                loading={Boolean(detailUser?.userId) && loadingUserId === detailUser.userId}
                open={Boolean(detailUser)}
                user={detailUser}
                onClose={closeAppUserDetail}
            />
        </AppUserDetailContext.Provider>
    );
}

function AppUserDetailDrawer({ loading, onClose, open, user }) {
    if (!open || !user) {
        return null;
    }

    return (
        <SideDrawer open={open} title="用户详情" width="wide" onClose={onClose}>
            <div className={styles.detailHero}>
                <AdminUserIdentity user={user} size="large" />
                <AppUserStatus status={user.status} />
            </div>
            {loading ? <div className={styles.detailLoading}>正在刷新用户详情...</div> : null}
            <section className={styles.detailSection}>
                <h3 className={styles.detailSectionTitle}>身份信息</h3>
                <div className={styles.detailGrid}>
                    <DetailItem label="用户 ID" value={user.userId} />
                    <DetailItem label="短 ID" value={user.defaultDisplayUserId || user.displayUserId || user.userId} />
                    <DetailItem label="靓号" value={<PrettyValue user={user} />} />
                    <DetailItem label="靓号记录 ID" value={user.prettyId} />
                    <DetailItem label="昵称" value={user.username} />
                    <DetailItem label="性别" value={formatGender(user.gender)} />
                </div>
            </section>
            <section className={styles.detailSection}>
                <h3 className={styles.detailSectionTitle}>账号状态</h3>
                <div className={styles.detailGrid}>
                    <DetailItem label="状态" value={appUserStatusLabels[user.status] || user.status || "-"} />
                    <DetailItem label="金币" value={formatNumber(user.coin)} />
                    <DetailItem label="钻石" value={formatNumber(user.diamond)} />
                    <DetailItem label="国家" value={formatCountry(user)} />
                    <DetailItem
                        label="区域"
                        value={user.regionName || (user.regionId ? `区域 ${user.regionId}` : "-")}
                    />
                    <DetailItem label="最近活跃" value={formatMillis(user.lastActiveAtMs)} />
                    <DetailItem label="创建时间" value={formatMillis(user.createdAtMs)} />
                    <DetailItem label="更新时间" value={formatMillis(user.updatedAtMs)} />
                </div>
            </section>
        </SideDrawer>
    );
}

function DetailItem({ label, value }) {
    const isElement = value && typeof value === "object";
    return (
        <div className={styles.detailItem}>
            <span className={styles.detailLabel}>{label}</span>
            <span className={styles.detailValue}>
                {isElement ? value : value === undefined || value === null || value === "" ? "-" : value}
            </span>
        </div>
    );
}

function PrettyValue({ user }) {
    if (!user.prettyId || !user.prettyDisplayUserId) {
        return "-";
    }
    return <AdminPrettyDisplayID prettyDisplayUserId={user.prettyDisplayUserId} prettyId={user.prettyId} />;
}

function AppUserStatus({ status }) {
    const tone = status === "active" ? "running" : "danger";
    return (
        <span className={`status-badge status-badge--${tone}`}>
            <span className="status-point" />
            {appUserStatusLabels[status] || status || "-"}
        </span>
    );
}

function normalizeDetailSeed(source) {
    if (source === undefined || source === null) {
        return {};
    }
    if (typeof source === "string" || typeof source === "number") {
        return { userId: String(source).trim() };
    }

    const userId = firstNonEmpty(
        source.userId,
        source.user_id,
        source.assignedUserId,
        source.assigned_user_id,
        source.targetUserId,
        source.target_user_id,
    );

    return {
        ...source,
        avatar: firstNonEmpty(source.avatar),
        defaultDisplayUserId: firstNonEmpty(source.defaultDisplayUserId, source.default_display_user_id),
        displayUserId: firstNonEmpty(source.displayUserId, source.display_user_id),
        prettyDisplayUserId: firstNonEmpty(source.prettyDisplayUserId, source.pretty_display_user_id),
        prettyId: firstNonEmpty(source.prettyId, source.pretty_id),
        userId,
        username: firstNonEmpty(source.username, source.name, source.account),
    };
}

function formatCountry(user) {
    return user.countryDisplayName || user.countryName || user.country || "-";
}

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 formatNumber(value) {
    const number = Number(value || 0);
    return Number.isFinite(number) ? number.toLocaleString() : "-";
}

function firstNonEmpty(...values) {
    for (const value of values) {
        const normalized = String(value ?? "").trim();
        if (normalized) {
            return normalized;
        }
    }
    return "";
}
