import PersonOutlineOutlined from "@mui/icons-material/PersonOutlineOutlined";
import { useAppUserDetail } from "@/features/app-users/components/AppUserDetailContext.jsx";
import styles from "@/shared/ui/AdminUserIdentity.module.css";

export function AdminUserIdentity({
    avatar,
    className = "",
    defaultDisplayUserId,
    displayUserId,
    name,
    namePrefix,
    onClick,
    openInAppUserDetail = false,
    prettyDisplayUserId,
    prettyId,
    rows,
    size = "table",
    user,
    userId,
}) {
    const { openAppUserDetail } = useAppUserDetail();
    const normalized = normalizeUserIdentity({
        avatar,
        defaultDisplayUserId,
        displayUserId,
        name,
        prettyDisplayUserId,
        prettyId,
        user,
        userId,
    });
    const visibleRows = Array.isArray(rows)
        ? resolveVisibleRows(rows, normalized)
        : [normalized.shortId].filter(Boolean);
    if (!normalized.hasIdentity) {
        return <span className={[styles.empty, className].filter(Boolean).join(" ")}>-</span>;
    }
    const shouldOpenAppUserDetail = openInAppUserDetail && normalized.userId && openAppUserDetail;
    const Root = onClick || shouldOpenAppUserDetail ? "button" : "div";
    const rootProps = resolveRootProps({
        displayName: normalized.displayName,
        onClick,
        openAppUserDetail,
        shouldOpenAppUserDetail,
        user: normalized.detailUser,
    });

    return (
        <Root
            className={[
                styles.root,
                size === "large" ? styles.large : "",
                onClick || shouldOpenAppUserDetail ? styles.button : "",
                shouldOpenAppUserDetail ? styles.link : "",
                onClick || shouldOpenAppUserDetail ? styles.clickable : "",
                className,
            ]
                .filter(Boolean)
                .join(" ")}
            {...rootProps}
        >
            <span className={styles.avatar}>
                {normalized.avatar ? (
                    <img src={normalized.avatar} alt="" />
                ) : (
                    <PersonOutlineOutlined fontSize="small" />
                )}
            </span>
            <div className={styles.text}>
                <div className={styles.nameLine}>
                    {namePrefix ? <span className={styles.namePrefix}>{namePrefix}</span> : null}
                    <span className={styles.name}>{normalized.displayName}</span>
                </div>
                {visibleRows.length ? (
                    <div className={styles.idLine}>
                        <span className={styles.idText}>{visibleRows[0]}</span>
                        {normalized.hasPretty ? (
                            <AdminPrettyDisplayID
                                prettyDisplayUserId={normalized.prettyDisplayUserId}
                                prettyId={normalized.prettyId}
                            />
                        ) : null}
                    </div>
                ) : normalized.hasPretty ? (
                    <div className={styles.idLine}>
                        <AdminPrettyDisplayID
                            prettyDisplayUserId={normalized.prettyDisplayUserId}
                            prettyId={normalized.prettyId}
                        />
                    </div>
                ) : null}
                {visibleRows.slice(1).map((row, index) => (
                    <span className={styles.extraRow} key={`${row}-${index}`}>
                        {row}
                    </span>
                ))}
            </div>
        </Root>
    );
}

export function AdminPrettyDisplayID({ prettyDisplayUserId, prettyId }) {
    const prettyValue = String(prettyDisplayUserId || "").trim();
    const recordId = String(prettyId || "").trim();
    if (!prettyValue || !recordId) {
        return null;
    }

    return (
        <span className={styles.prettyBadge} title={`靓号 ${prettyValue} · ${recordId}`}>
            <span className={styles.prettyValue}>{prettyValue}</span>
        </span>
    );
}

function normalizeUserIdentity({
    avatar,
    defaultDisplayUserId,
    displayUserId,
    name,
    prettyDisplayUserId,
    prettyId,
    user,
    userId,
}) {
    const source = user || {};
    // 后台各模块的数据来源不统一：新接口是 camelCase，部分老接口仍透传 snake_case。
    // 这里在公共入口一次性归一化，0 是后台未绑定用户的哨兵值，不能再被当成真实用户渲染和点击。
    const resolvedUserId = firstNonEmptyIdentityValue(
        userId,
        source.userId,
        source.user_id,
        source.assignedUserId,
        source.assigned_user_id,
        source.targetUserId,
        source.target_user_id,
    );
    const resolvedDefaultDisplayUserId = firstNonEmptyIdentityValue(
        defaultDisplayUserId,
        source.defaultDisplayUserId,
        source.default_display_user_id,
    );
    const resolvedDisplayUserId = firstNonEmptyIdentityValue(
        displayUserId,
        source.displayUserId,
        source.display_user_id,
        resolvedDefaultDisplayUserId,
        resolvedUserId,
    );
    const resolvedPrettyId = firstNonEmpty(prettyId, source.prettyId, source.pretty_id);
    const resolvedPrettyDisplayUserId = firstNonEmpty(
        prettyDisplayUserId,
        source.prettyDisplayUserId,
        source.pretty_display_user_id,
    );
    // 靓号只在 record id 和展示内容同时存在时显示；短号行优先取 defaultDisplayUserId，避免当前展示号被靓号覆盖后重复展示。
    const hasPretty = Boolean(resolvedPrettyId && resolvedPrettyDisplayUserId);
    const resolvedShortId = hasPretty
        ? firstNonEmpty(resolvedDefaultDisplayUserId, resolvedUserId, resolvedDisplayUserId)
        : firstNonEmpty(resolvedDisplayUserId, resolvedDefaultDisplayUserId, resolvedUserId);
    const resolvedAvatar = firstNonEmpty(avatar, source.avatar);
    const explicitName = firstNonEmpty(
        name,
        source.username,
        source.name,
        source.account,
    );
    const displayName = firstNonEmpty(
        explicitName,
        resolvedDisplayUserId,
        resolvedUserId,
        "-",
    );
    const hasIdentity = Boolean(
        resolvedAvatar || explicitName || resolvedDisplayUserId || resolvedDefaultDisplayUserId || resolvedUserId,
    );

    return {
        avatar: resolvedAvatar,
        detailUser: {
            ...source,
            avatar: resolvedAvatar,
            defaultDisplayUserId: resolvedDefaultDisplayUserId,
            displayUserId: resolvedDisplayUserId,
            prettyDisplayUserId: resolvedPrettyDisplayUserId,
            prettyId: resolvedPrettyId,
            userId: resolvedUserId,
            username: explicitName,
        },
        displayUserId: resolvedDisplayUserId,
        displayName,
        hasPretty,
        hasIdentity,
        prettyDisplayUserId: resolvedPrettyDisplayUserId,
        prettyId: resolvedPrettyId,
        shortId: resolvedShortId || "-",
        userId: resolvedUserId,
    };
}

function resolveVisibleRows(rows, normalized) {
    const visibleRows = rows.map((row) => String(row || "").trim()).filter(Boolean);
    if (
        normalized.hasPretty &&
        normalized.shortId &&
        normalized.displayUserId &&
        visibleRows[0] === normalized.displayUserId &&
        normalized.shortId !== normalized.displayUserId
    ) {
        return [normalized.shortId, ...visibleRows.slice(1)];
    }
    return visibleRows;
}

function resolveRootProps({ displayName, onClick, openAppUserDetail, shouldOpenAppUserDetail, user }) {
    if (onClick) {
        return {
            "aria-label": `查看用户 ${displayName}`,
            onClick: (event) => {
                event.stopPropagation();
                onClick(event);
            },
            type: "button",
        };
    }
    if (shouldOpenAppUserDetail) {
        return {
            "aria-label": `查看用户详情 ${displayName}`,
            onClick: (event) => {
                event.stopPropagation();
                openAppUserDetail(user);
            },
            type: "button",
        };
    }
    return {};
}

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

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