import ArrowBackOutlined from "@mui/icons-material/ArrowBackOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import { useCallback } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { PageSkeleton } from "@/shared/ui/PageSkeleton.jsx";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { getAppUser } from "@/features/app-users/api";
import { AppUserDetailView } from "@/features/app-users/components/AppUserDetailView.jsx";
import styles from "@/features/app-users/app-users.module.css";

export function AppUserDetailPage() {
    const navigate = useNavigate();
    const location = useLocation();
    const { userId = "" } = useParams();
    const normalizedUserId = String(userId).trim();
    const loadUser = useCallback(() => getAppUser(normalizedUserId), [normalizedUserId]);
    const { data, error, loading, reload } = useAdminQuery(loadUser, {
        enabled: Boolean(normalizedUserId),
        errorMessage: "加载用户详情失败",
        initialData: null,
        queryKey: ["app-users", "detail", normalizedUserId],
    });

    if (loading && !data) {
        return <PageSkeleton />;
    }

    const pageError = normalizedUserId ? error : "缺少用户 ID";
    const returnPath = resolveReturnPath(location.state?.from);

    return (
        <div className={styles.detailPageRoot}>
            <div className={styles.detailPageToolbar}>
                <div className={styles.detailPageTitleGroup}>
                    <Button onClick={() => navigate(returnPath)}>
                        <ArrowBackOutlined fontSize="small" />
                        返回用户列表
                    </Button>
                    <h1>用户详情</h1>
                </div>
                <Button disabled={loading || !normalizedUserId} onClick={reload}>
                    <RefreshOutlined fontSize="small" />
                    刷新
                </Button>
            </div>
            <div className={styles.detailPageContent}>
                <DataState error={pageError} loading={false} onRetry={normalizedUserId ? reload : undefined}>
                    {data ? <AppUserDetailView mode="page" user={data} onReloadUser={reload} /> : null}
                </DataState>
            </div>
        </div>
    );
}

function resolveReturnPath(value) {
    const path = String(value || "");
    // 只恢复站内绝对路径，避免路由 state 被外部输入污染后形成开放跳转。
    return path.startsWith("/") && !path.startsWith("//") ? path : "/app/users";
}
