import { useCallback, useMemo, useRef, useState } from "react";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { getAppUser } from "@/features/app-users/api";
import { AppUserDetailContext } from "@/features/app-users/components/AppUserDetailContext.jsx";
import { AppUserDetailView } from "@/features/app-users/components/AppUserDetailView.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}
                onReloadUser={() => openAppUserDetail(detailUser)}
            />
        </AppUserDetailContext.Provider>
    );
}

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

    return (
        <SideDrawer
            contentClassName={styles.detailDrawerBody}
            open={open}
            title="用户详情"
            width="detail"
            onClose={onClose}
        >
            <AppUserDetailView
                fullDetailsHref={`/app/users/${encodeURIComponent(user.userId)}`}
                loading={loading}
                user={user}
                onOpenFullDetails={onClose}
                onReloadUser={onReloadUser}
            />
        </SideDrawer>
    );
}

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 firstNonEmpty(...values) {
    for (const value of values) {
        const normalized = String(value ?? "").trim();
        if (normalized) {
            return normalized;
        }
    }
    return "";
}
