2025-10-23 01:39:29 -03:00

75 lines
2.5 KiB
TypeScript

// Caminho: app/(patient)/layout.tsx (Refatoração Sugerida)
"use client";
import type React from "react";
import { useState, useEffect, createContext, useContext } from "react";
import { useRouter } from "next/navigation";
import { usuariosApi, User } from "@/services/usuariosApi"; // Assumindo que User é exportado
import DashboardLayout, { UserProfile } from "@/components/layout/DashboardLayout";
import { dashboardConfig } from "@/config/dashboard.config";
// --- Contexto para compartilhar dados do usuário autenticado ---
interface PatientAuthContextType {
user: User | null;
userProfile: UserProfile | null;
isLoading: boolean;
}
const PatientAuthContext = createContext<PatientAuthContextType | undefined>(undefined);
// Hook customizado para facilitar o acesso ao contexto nas páginas filhas
export const usePatientAuth = () => {
const context = useContext(PatientAuthContext);
if (!context) {
throw new Error("usePatientAuth deve ser usado dentro de um PatientLayout");
}
return context;
};
// ----------------------------------------------------------------
export default function PatientLayout({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
useEffect(() => {
const checkAuthentication = async () => {
try {
const userData = await usuariosApi.getCurrentUser();
if (!userData) throw new Error("Usuário não autenticado.");
setUser(userData);
} catch (error) {
console.error("Falha na autenticação para paciente:", error);
router.push("/login");
} finally {
setIsLoading(false);
}
};
checkAuthentication();
}, [router]);
if (isLoading) {
return (
<div className="flex h-screen w-full items-center justify-center bg-background">
<p className="text-muted-foreground">Verificando autenticação...</p>
</div>
);
}
if (!user) {
return null; // Evita renderizar o layout durante o redirecionamento
}
// A formatação do perfil agora é feita aqui, com os dados já carregados
const userProfile = dashboardConfig.patient.getUserProfile(user);
const menuItems = dashboardConfig.patient.menuItems;
const contextValue = { user, userProfile, isLoading };
return (
<PatientAuthContext.Provider value={contextValue}>
<DashboardLayout menuItems={menuItems} userProfile={userProfile}>
{children}
</DashboardLayout>
</PatientAuthContext.Provider>
);
}