Merge pull request #40 from m1guelmcf/Stage

Stage
This commit is contained in:
DaniloSts 2025-12-04 13:15:56 -03:00 committed by GitHub
commit 979bb0db7f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 2227 additions and 1934 deletions

View File

@ -19,20 +19,25 @@ interface AccessibilityContextProps {
const AccessibilityContext = createContext<AccessibilityContextProps | undefined>(undefined);
export const AccessibilityProvider = ({ children }: { children: ReactNode }) => {
const [theme, setThemeState] = useState<Theme>('light');
const [contrast, setContrastState] = useState<Contrast>('normal');
const [fontSize, setFontSize] = useState<number>(16);
useEffect(() => {
const storedTheme = (localStorage.getItem('accessibility-theme') as Theme) || 'light';
const storedContrast = (localStorage.getItem('accessibility-contrast') as Contrast) || 'normal';
const storedSize = localStorage.getItem('accessibility-font-size');
setThemeState(storedTheme);
setContrastState(storedContrast);
if (storedSize) {
setFontSize(parseFloat(storedSize));
const [theme, setThemeState] = useState<Theme>(() => {
if (typeof window !== 'undefined') {
return (localStorage.getItem('accessibility-theme') as Theme) || 'light';
}
}, []);
return 'light';
});
const [contrast, setContrastState] = useState<Contrast>(() => {
if (typeof window !== 'undefined') {
return (localStorage.getItem('accessibility-contrast') as Contrast) || 'normal';
}
return 'normal';
});
const [fontSize, setFontSize] = useState<number>(() => {
if (typeof window !== 'undefined') {
const storedSize = localStorage.getItem('accessibility-font-size');
return storedSize ? parseFloat(storedSize) : 16;
}
return 16;
});
useEffect(() => {
const root = document.documentElement;

View File

@ -21,7 +21,7 @@ import {
} from "@/components/ui/alert-dialog";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useEffect, useState, useMemo } from "react"; // Adicionado useMemo
import { toast } from "@/hooks/use-toast";
import { useAuthLayout } from "@/hooks/useAuthLayout";
@ -38,7 +38,6 @@ import Sidebar from "@/components/Sidebar";
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
// --- TIPOS ADICIONADOS PARA CORREÇÃO ---
type Appointment = {
id: string;
doctor_id: string;
@ -50,7 +49,6 @@ type Appointment = {
type EnrichedAppointment = Appointment & {
patientName: string;
};
// --- FIM DOS TIPOS ADICIONADOS ---
type Availability = {
id: string;
@ -142,14 +140,17 @@ interface Exception {
created_by: string;
}
// Minimal type for Patient, adjust if more fields are needed
type Patient = {
id: string;
full_name: string;
};
export default function PatientDashboard() {
const { user } = useAuthLayout({ requiredRole: ['medico'] });
export default function DoctorDashboard() {
// --- CORREÇÃO CRÍTICA DO LOOP ---
// Usamos useMemo para garantir que o array de roles seja uma referência estável
// e não dispare o useEffect do useAuthLayout infinitamente.
const requiredRoles = useMemo(() => ['medico'], []);
const { user } = useAuthLayout({ requiredRole: requiredRoles });
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
const [userData, setUserData] = useState<UserData>();
@ -218,7 +219,7 @@ export default function PatientDashboard() {
};
fetchData();
}, [user]);
}, [user?.id]);
function findDoctorById(id: string, doctors: Doctor[]) {
return doctors.find((doctor) => doctor.user_id === id);
@ -264,8 +265,8 @@ export default function PatientDashboard() {
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<p className="text-gray-600">
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
@ -325,7 +326,7 @@ export default function PatientDashboard() {
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/doctor/medicos/consultas">
<Link href="/doctor/consultas">
<Button className="w-full justify-start">
<Calendar className="mr-2 h-4 w-4" />
Ver Minhas Consultas
@ -367,21 +368,21 @@ export default function PatientDashboard() {
return (
<div key={ex.id} className="space-y-4">
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
<div className="flex flex-col items-center justify-between p-3 bg-primary/10 rounded-lg shadow-sm">
<div className="text-center">
<p className="font-semibold capitalize">{date}</p>
<p className="text-sm text-gray-600">
<p className="text-sm text-muted-foreground">
{startTime && endTime
? `${startTime} - ${endTime}`
: "Dia todo"}
</p>
</div>
<div className="text-center mt-2">
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
<p className="text-xs text-gray-500 italic">{ex.reason || "Sem motivo especificado"}</p>
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-destructive" : "text-primary"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
<p className="text-xs text-muted-foreground italic">{ex.reason || "Sem motivo especificado"}</p>
</div>
<div>
<Button className="text-red-600" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
<Button className="text-destructive" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
<Trash2></Trash2>
</Button>
</div>
@ -390,7 +391,7 @@ export default function PatientDashboard() {
);
})
) : (
<p className="text-sm text-gray-400 italic col-span-7 text-center">Nenhuma exceção registrada.</p>
<p className="text-sm text-muted-foreground italic col-span-7 text-center">Nenhuma exceção registrada.</p>
)}
</CardContent>
</Card>
@ -403,7 +404,7 @@ export default function PatientDashboard() {
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-red-600 hover:bg-red-700">
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-destructive hover:bg-destructive/90">
Excluir
</AlertDialogAction>
</AlertDialogFooter>

View File

@ -149,12 +149,12 @@ export default function ExceptionPage() {
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Adicione exceções</h1>
<p className="text-gray-600">Altere a disponibilidade em casos especiais para o Dr. João Silva</p>
<h1 className="text-3xl font-bold text-foreground">Adicione exceções</h1>
<p className="text-muted-foreground">Altere a disponibilidade em casos especiais para o Dr. João Silva</p>
</div>
<div className="flex justify-between items-center">
<h2 className="text-xl font-semibold">Consultas para: {displayDate}</h2>
<h2 className="text-xl font-semibold text-foreground">Consultas para: {displayDate}</h2>
<Button disabled={isLoading} variant="outline" size="sm">
<RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
Atualizar Agenda
@ -171,7 +171,7 @@ export default function ExceptionPage() {
<CalendarIcon className="mr-2 h-5 w-5" />
Calendário
</CardTitle>
<p className="text-sm text-gray-500">Selecione a data desejada.</p>
<p className="text-sm text-muted-foreground">Selecione a data desejada.</p>
</CardHeader>
<CardContent className="flex justify-center p-2">
<Calendar
@ -194,23 +194,23 @@ export default function ExceptionPage() {
{/* COLUNA 2: FORM PARA ADICIONAR EXCEÇÃO */}
<div className="lg:col-span-2 space-y-4">
{isLoading ? (
<p className="text-center text-lg text-gray-500">Carregando a agenda...</p>
<p className="text-center text-lg text-muted-foreground">Carregando a agenda...</p>
) : !selectedCalendarDate ? (
<p className="text-center text-lg text-gray-500">Selecione uma data.</p>
<p className="text-center text-lg text-muted-foreground">Selecione uma data.</p>
) : (
<form className="space-y-6" onSubmit={handleSubmit}>
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
<div className="bg-card rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Dados </h2>
<div className="space-y-6">
<div className="grid md:grid-cols-5 gap-6">
<div>
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-foreground">
Horario De Entrada
</Label>
<Input type="time" id="horarioEntrada" name="horarioEntrada" className="mt-1" />
</div>
<div>
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
<Label htmlFor="horarioSaida" className="text-sm font-medium text-foreground">
Horario De Saida
</Label>
<Input type="time" id="horarioSaida" name="horarioSaida" className="mt-1" />
@ -218,7 +218,7 @@ export default function ExceptionPage() {
</div>
<div>
<Label htmlFor="tipo" className="text-sm font-medium text-gray-700">
<Label htmlFor="tipo" className="text-sm font-medium text-foreground">
Tipo
</Label>
<Select onValueChange={(value) => setTipo(value)} value={tipo}>
@ -232,7 +232,7 @@ export default function ExceptionPage() {
</Select>
</div>
<div>
<Label htmlFor="reason" className="text-sm font-medium text-gray-700">
<Label htmlFor="reason" className="text-sm font-medium text-foreground">
Motivo
</Label>
<Input type="textarea" id="reason" name="reason" required className="mt-1" />
@ -244,7 +244,7 @@ export default function ExceptionPage() {
<Link href="/doctor/disponibilidade">
<Button variant="outline">Cancelar</Button>
</Link>
<Button type="submit" className="bg-green-600 hover:bg-green-700">
<Button type="submit" className="bg-green-600 hover:bg-green-700 text-white">
Salvar Exceção
</Button>
</div>

View File

@ -379,23 +379,23 @@ export default function AvailabilityPage() {
<div className="space-y-6 flex-1 overflow-y-auto p-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">
<h1 className="text-2xl font-bold">
Definir Disponibilidade
</h1>
<p className="text-gray-600">
<p className="text-muted-foreground">
Defina sua disponibilidade para consultas{" "}
</p>
</div>
</div>
<form className="space-y-6" onSubmit={handleSubmit}>
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Dados </h2>
<div className="space-y-6">
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
<div>
<Label className="text-sm font-medium text-gray-700">
<Label className="text-sm font-medium">
Dia Da Semana
</Label>
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
@ -405,7 +405,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="monday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Segunda</span>
</label>
@ -414,7 +414,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="tuesday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Terça</span>
</label>
@ -423,7 +423,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="wednesday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Quarta</span>
</label>
@ -432,7 +432,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="thursday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Quinta</span>
</label>
@ -441,7 +441,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="friday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Sexta</span>
</label>
@ -450,7 +450,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="saturday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Sábado</span>
</label>
@ -459,7 +459,7 @@ export default function AvailabilityPage() {
type="radio"
name="weekday"
value="sunday"
className="text-blue-600"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Domingo</span>
</label>
@ -472,7 +472,7 @@ export default function AvailabilityPage() {
<div>
<Label
htmlFor="horarioEntrada"
className="text-sm font-medium text-gray-700"
className="text-sm font-medium"
>
Horario De Entrada
</Label>
@ -487,7 +487,7 @@ export default function AvailabilityPage() {
<div>
<Label
htmlFor="horarioSaida"
className="text-sm font-medium text-gray-700"
className="text-sm font-medium"
>
Horario De Saida
</Label>
@ -502,9 +502,9 @@ export default function AvailabilityPage() {
<div>
<Label
htmlFor="duracaoConsulta"
className="text-sm font-medium text-gray-700"
className="text-sm font-medium whitespace-nowrap"
>
Duração Da Consulta (min)
Duração da Consulta(min)
</Label>
<Input
type="number"
@ -520,7 +520,7 @@ export default function AvailabilityPage() {
<div>
<Label
htmlFor="modalidadeConsulta"
className="text-sm font-medium text-gray-700"
className="text-sm font-medium"
>
Modalidade De Consulta
</Label>
@ -551,7 +551,7 @@ export default function AvailabilityPage() {
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
</Link>
<Button type="submit" className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto">
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
Salvar Disponibilidade
</Button>
</div>
@ -571,15 +571,15 @@ export default function AvailabilityPage() {
const times = schedule[day] || [];
return (
<div key={day} className="space-y-4">
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg h-full">
<p className="font-medium capitalize text-center mb-2">{weekdaysPT[day]}</p>
<div className="text-center w-full">
<div className="flex flex-col items-center justify-start p-3 bg-primary/10 rounded-lg min-h-[76px] ">
<p className="font-medium capitalize text-center ">{weekdaysPT[day]}</p>
<div className="text-center w-full mt-2">
{times.length > 0 ? (
times.map((t, i) => (
<div key={i}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<p className="text-sm text-gray-600 cursor-pointer rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
<p className="text-sm text-muted-foreground cursor-pointer rounded hover:text-accent-foreground hover:bg-muted transition-colors duration-150">
{formatTime(t.start)} - {formatTime(t.end)}
</p>
</DropdownMenuTrigger>
@ -590,7 +590,7 @@ export default function AvailabilityPage() {
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => openDeleteDialog(t, day)}
className="text-red-600 focus:bg-red-50 focus:text-red-600">
className="text-destructive focus:bg-destructive/10 focus:text-destructive">
<Trash2 className="w-4 h-4 mr-2" />
Excluir
</DropdownMenuItem>
@ -599,7 +599,7 @@ export default function AvailabilityPage() {
</div>
))
) : (
<p className="text-sm text-gray-400 italic">Sem horário</p>
<p className="text-sm text-muted-foreground italic">Sem horário</p>
)}
</div>
</div>
@ -619,7 +619,7 @@ export default function AvailabilityPage() {
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => selectedAvailability && handleDeleteAvailability(selectedAvailability.id)} className="bg-red-600 hover:bg-red-700">
<AlertDialogAction onClick={() => selectedAvailability && handleDeleteAvailability(selectedAvailability.id)} className="bg-destructive hover:bg-destructive/90">
Excluir
</AlertDialogAction>
</AlertDialogFooter>

View File

@ -16,8 +16,8 @@
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--destructive-foreground: oklch(0.577 0.245 27.325);
--destructive: oklch(0.637 0.237 25.331);
--destructive-foreground: oklch(0.985 0 0);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
@ -52,8 +52,8 @@
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.396 0.141 25.723);
--destructive-foreground: oklch(0.637 0.237 25.331);
--destructive: oklch(0.7 0.25 25);
--destructive-foreground: oklch(0.985 0 0);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
@ -87,7 +87,7 @@
--muted-foreground: oklch(1 0.5 100);
--accent: oklch(0 0 0);
--accent-foreground: oklch(1 0.5 100);
--destructive: oklch(0.5 0.3 30);
--destructive: oklch(0.8 0.5 25);
--destructive-foreground: oklch(0 0 0);
--border: oklch(1 0.5 100);
--input: oklch(0 0 0);

View File

@ -4,11 +4,7 @@ import { GeistMono } from "geist/font/mono";
import { Analytics } from "@vercel/analytics/next";
import "./globals.css";
import { Toaster } from "@/components/ui/toaster";
// [PASSO 1.2] - Importando o nosso provider
import { AppointmentsProvider } from "./context/AppointmentsContext";
import { AccessibilityProvider } from "./context/AccessibilityContext";
import { AccessibilityModal } from "@/components/accessibility-modal";
import { ThemeInitializer } from "@/components/theme-initializer";
import { Providers } from "./providers";
export default function RootLayout({
children,
@ -18,12 +14,7 @@ export default function RootLayout({
return (
<html lang="en" suppressHydrationWarning>
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
{/* [PASSO 1.2] - Envolvendo a aplicação com o provider */}
<ThemeInitializer />
<AccessibilityProvider>
<AppointmentsProvider>{children}</AppointmentsProvider>
<AccessibilityModal />
</AccessibilityProvider>
<Providers>{children}</Providers>
<Analytics />
<Toaster />
</body>

View File

@ -97,7 +97,7 @@ export default function LoginPage() {
</div>
{/* O contêiner principal que agora terá a sombra e o estilo de card */}
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl">
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl border-2 border-border mt-8">
{/* NOVO: Bloco da Logo e Nome (Painel Esquerdo) */}
<div className="flex items-center justify-center space-x-3 mb-8">
<img
@ -155,6 +155,7 @@ export default function LoginPage() {
fill
style={{ objectFit: "cover" }}
priority
className="dark:opacity-80"
/>
{/* Camada de sobreposição para escurecer a imagem e destacar o texto */}
<div className="absolute inset-0 bg-primary/80 flex flex-col items-start justify-end p-12 text-left">

View File

@ -94,8 +94,8 @@ export default function ManagerDashboard() {
<div className="space-y-6">
{/* Cabeçalho */}
<div>
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<p className="text-gray-600">
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
@ -114,7 +114,7 @@ export default function ManagerDashboard() {
</CardHeader>
<CardContent>
{loadingUser ? (
<div className="text-gray-500 text-sm">
<div className="text-muted-foreground text-sm">
Carregando usuário...
</div>
) : firstUser ? (
@ -127,7 +127,7 @@ export default function ManagerDashboard() {
</p>
</>
) : (
<div className="text-sm text-gray-500">
<div className="text-sm text-muted-foreground">
Nenhum usuário encontrado
</div>
)}
@ -159,15 +159,15 @@ export default function ManagerDashboard() {
</CardHeader>
<CardContent className="space-y-4">
<Link href="/manager/home">
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
<User className="mr-2 h-4 w-4 text-white" />
<Button className="w-full justify-start">
<User className="mr-2 h-4 w-4" />
Gestão de Médicos
</Button>
</Link>
<Link href="/manager/usuario">
<Button
variant="outline"
className="w-full justify-start bg-transparent"
className="w-full justify-start"
>
<User className="mr-2 h-4 w-4" />
Usuários Cadastrados
@ -176,7 +176,7 @@ export default function ManagerDashboard() {
<Link href="/manager/home/novo">
<Button
variant="outline"
className="w-full justify-start bg-transparent"
className="w-full justify-start"
>
<Plus className="mr-2 h-4 w-4" />
Adicionar Novo Médico
@ -185,7 +185,7 @@ export default function ManagerDashboard() {
<Link href="/manager/usuario/novo">
<Button
variant="outline"
className="w-full justify-start bg-transparent"
className="w-full justify-start"
>
<Plus className="mr-2 h-4 w-4" />
Criar novo Usuário
@ -204,9 +204,9 @@ export default function ManagerDashboard() {
</CardHeader>
<CardContent>
{loadingDoctors ? (
<p className="text-sm text-gray-500">Carregando médicos...</p>
<p className="text-sm text-muted-foreground">Carregando médicos...</p>
) : doctors.length === 0 ? (
<p className="text-sm text-gray-500">
<p className="text-sm text-muted-foreground">
Nenhum médico cadastrado.
</p>
) : (
@ -214,18 +214,18 @@ export default function ManagerDashboard() {
{doctors.map((doc, index) => (
<div
key={index}
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
className="flex items-center justify-between p-3 bg-secondary rounded-lg border"
>
<div>
<p className="font-medium">
{doc.full_name || "Sem nome"}
</p>
<p className="text-sm text-gray-600">
<p className="text-sm text-muted-foreground">
{doc.specialty || "Sem especialidade"}
</p>
</div>
<div className="text-right">
<p className="font-medium text-green-700">
<p className="font-medium text-primary">
{doc.active ? "Ativo" : "Inativo"}
</p>
</div>

View File

@ -84,7 +84,7 @@ export default function AllAvailabilities() {
if (loading) {
return (
<Sidebar>
<div className="p-6 text-gray-500">Carregando dados...</div>
<div className="p-6 text-muted-foreground">Carregando dados...</div>
</Sidebar>
);
}
@ -92,7 +92,7 @@ export default function AllAvailabilities() {
if (!doctors || !availabilities) {
return (
<Sidebar>
<div className="p-6 text-red-600 font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
<div className="p-6 text-destructive font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
</Sidebar>
);
}
@ -101,8 +101,8 @@ export default function AllAvailabilities() {
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Disponibilidade dos Médicos</h1>
<p className="text-gray-600">Visualize a agenda semanal individual de cada médico.</p>
<h1 className="text-3xl font-bold">Disponibilidade dos Médicos</h1>
<p className="text-muted-foreground">Visualize a agenda semanal individual de cada médico.</p>
</div>
<Card>
<CardContent>
@ -170,7 +170,7 @@ export default function AllAvailabilities() {
Anterior
</Button>
<span className="text-gray-700 font-medium">
<span className="text-muted-foreground font-medium">
Página {page} de {totalPages}
</span>

View File

@ -209,8 +209,8 @@ export default function EditarMedicoPage() {
return (
<Sidebar>
<div className="flex justify-center items-center h-full w-full py-16">
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
<p className="ml-2 text-gray-600">Carregando dados do médico...</p>
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="ml-2 text-muted-foreground">Carregando dados do médico...</p>
</div>
</Sidebar>
);
@ -221,10 +221,10 @@ export default function EditarMedicoPage() {
<div className="w-full space-y-6 p-4 md:p-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
<h1 className="text-2xl font-bold text-foreground">
Editar Médico: <span className="text-primary">{formData.nomeCompleto}</span>
</h1>
<p className="text-sm text-gray-500">
<p className="text-sm text-muted-foreground">
Atualize as informações do médico
</p>
</div>
@ -239,14 +239,14 @@ export default function EditarMedicoPage() {
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
<div className="p-3 rounded-lg border bg-destructive/10 text-destructive border-destructive/30">
<p className="font-medium">Erro na Atualização:</p>
<p className="text-sm">{error}</p>
</div>
)}
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
Dados Principais e Pessoais
</h2>
<div className="grid md:grid-cols-4 gap-4">
@ -348,8 +348,8 @@ export default function EditarMedicoPage() {
</div>
</div>
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
Contato e Endereço
</h2>
@ -452,8 +452,8 @@ export default function EditarMedicoPage() {
</div>
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
Observações (Apenas internas)
</h2>
<Textarea
@ -474,7 +474,7 @@ export default function EditarMedicoPage() {
</Link>
<Button
type="submit"
className="bg-green-600 hover:bg-green-700"
className="bg-primary hover:bg-primary/90"
disabled={isSaving}
>
{isSaving ? (

View File

@ -224,10 +224,10 @@ export default function DoctorsPage() {
{/* Cabeçalho */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">
<h1 className="text-2xl font-bold">
Médicos Cadastrados
</h1>
<p className="text-sm text-gray-500">
<p className="text-sm text-muted-foreground">
Gerencie todos os profissionais de saúde.
</p>
</div>
@ -270,54 +270,54 @@ export default function DoctorsPage() {
</FilterBar>
{/* Tabela de Médicos */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden hidden md:block">
<div className="bg-card rounded-lg border shadow-md overflow-hidden hidden md:block">
{loading ? (
<div className="p-8 text-center text-gray-500">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
<div className="p-8 text-center text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
Carregando médicos...
</div>
) : error ? (
<div className="p-8 text-center text-red-600">{error}</div>
<div className="p-8 text-center text-destructive">{error}</div>
) : filteredDoctors.length === 0 ? (
<div className="p-8 text-center text-gray-500">
<div className="p-8 text-center text-muted-foreground">
{doctors.length === 0
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.</>
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-primary hover:underline">Adicione um novo</Link>.</>
: "Nenhum médico encontrado com os filtros aplicados."
}
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full min-w-[600px]">
<thead className="bg-gray-50 border-b border-gray-200">
<thead className="bg-muted border-b">
<tr>
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Nome</th>
<th className="text-left p-2 md:p-4 font-medium text-gray-700">CRM</th>
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Especialidade</th>
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden lg:table-cell">Status</th>
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden xl:table-cell">Cidade/Estado</th>
<th className="text-right p-4 font-medium text-gray-700">Ações</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">Nome</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">CRM</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">Especialidade</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground hidden lg:table-cell">Status</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground hidden xl:table-cell">Cidade/Estado</th>
<th className="text-right p-4 font-medium text-muted-foreground">Ações</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
<tbody className="bg-card divide-y">
{currentItems.map((doctor) => (
<tr key={doctor.id} className="hover:bg-gray-50 transition">
<td className="px-4 py-3 font-medium text-gray-900">
<tr key={doctor.id} className="hover:bg-muted transition">
<td className="px-4 py-3 font-medium">
{doctor.full_name}
</td>
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">
<td className="px-4 py-3 text-muted-foreground hidden sm:table-cell">{doctor.crm}</td>
<td className="px-4 py-3 text-muted-foreground hidden md:table-cell">
{/* Exibe Especialidade Normalizada */}
{normalizeSpecialty(doctor.specialty)}
</td>
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">
<td className="px-4 py-3 text-muted-foreground hidden lg:table-cell">
<span className={`px-2 py-1 rounded-full text-xs ${
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
doctor.status === 'Ativo' ? 'bg-primary/10 text-primary' :
doctor.status === 'Inativo' ? 'bg-destructive/10 text-destructive' : 'bg-yellow-400/10 text-yellow-400'
}`}>
{doctor.status || "N/A"}
</span>
</td>
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
<td className="px-4 py-3 text-muted-foreground hidden xl:table-cell">
{(doctor.city || doctor.state)
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
: "N/A"}
@ -345,7 +345,7 @@ export default function DoctorsPage() {
<Calendar className="mr-2 h-4 w-4" />
Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(doctor.id)}>
<Trash2 className="mr-2 h-4 w-4" />
Excluir
</DropdownMenuItem>
@ -361,33 +361,33 @@ export default function DoctorsPage() {
</div>
{/* Cards de Médicos (Mobile) */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
<div className="bg-card rounded-lg border shadow-md p-4 block md:hidden">
{loading ? (
<div className="p-8 text-center text-gray-500">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
<div className="p-8 text-center text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
Carregando médicos...
</div>
) : error ? (
<div className="p-8 text-center text-red-600">{error}</div>
<div className="p-8 text-center text-destructive">{error}</div>
) : filteredDoctors.length === 0 ? (
<div className="p-8 text-center text-gray-500">
<div className="p-8 text-center text-muted-foreground">
{doctors.length === 0
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.</>
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-primary hover:underline">Adicione um novo</Link>.</>
: "Nenhum médico encontrado com os filtros aplicados."
}
</div>
) : (
<div className="space-y-4">
{currentItems.map((doctor) => (
<div key={doctor.id} className="bg-gray-50 rounded-lg p-4 flex justify-between items-center border border-gray-100">
<div key={doctor.id} className="bg-muted rounded-lg p-4 flex justify-between items-center border">
<div>
<div className="font-semibold text-gray-900">{doctor.full_name}</div>
<div className="text-xs text-gray-500 mb-1">{doctor.phone_mobile}</div>
<div className="text-sm text-gray-600">{normalizeSpecialty(doctor.specialty)}</div>
<div className="font-semibold">{doctor.full_name}</div>
<div className="text-xs text-muted-foreground mb-1">{doctor.phone_mobile}</div>
<div className="text-sm text-muted-foreground">{normalizeSpecialty(doctor.specialty)}</div>
<div className="text-xs mt-1">
<span className={`px-2 py-0.5 rounded-full text-xs ${
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
doctor.status === 'Ativo' ? 'bg-primary/10 text-primary' :
doctor.status === 'Inativo' ? 'bg-destructive/10 text-destructive' : 'bg-yellow-400/10 text-yellow-400'
}`}>
{doctor.status || "N/A"}
</span>
@ -397,7 +397,7 @@ export default function DoctorsPage() {
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<span className="sr-only">Abrir menu</span>
<div className="font-bold text-gray-500">...</div>
<div className="font-bold text-muted-foreground">...</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
@ -411,7 +411,7 @@ export default function DoctorsPage() {
Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(doctor.id)}>
<Trash2 className="mr-2 h-4 w-4" />
Excluir
</DropdownMenuItem>
@ -425,11 +425,11 @@ export default function DoctorsPage() {
{/* Paginação */}
{totalPages > 1 && (
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-white rounded-lg border border-gray-200 shadow-md">
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-card rounded-lg border shadow-md">
<button
onClick={goToPrevPage}
disabled={currentPage === 1}
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"< Anterior"}
</button>
@ -438,10 +438,10 @@ export default function DoctorsPage() {
<button
key={number}
onClick={() => paginate(number)}
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border ${
currentPage === number
? "bg-blue-600 text-white shadow-md border-blue-600"
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
? "bg-primary text-primary-foreground shadow-md border-primary"
: "bg-muted text-muted-foreground hover:bg-muted/90"
}`}
>
{number}
@ -451,7 +451,7 @@ export default function DoctorsPage() {
<button
onClick={goToNextPage}
disabled={currentPage === totalPages}
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"Próximo >"}
</button>
@ -467,7 +467,7 @@ export default function DoctorsPage() {
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
<AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
Excluir
</AlertDialogAction>
@ -484,7 +484,7 @@ export default function DoctorsPage() {
<AlertDialogTitle className="text-2xl">
{doctorDetails?.nome}
</AlertDialogTitle>
<AlertDialogDescription className="text-left text-gray-700">
<AlertDialogDescription className="text-left text-muted-foreground">
{doctorDetails && (
<div className="space-y-3 text-left">
<h3 className="font-semibold mt-2">
@ -537,7 +537,7 @@ export default function DoctorsPage() {
</div>
)}
{doctorDetails === null && !loading && (
<div className="text-red-600">Detalhes não disponíveis.</div>
<div className="text-destructive">Detalhes não disponíveis.</div>
)}
</AlertDialogDescription>
</AlertDialogHeader>

View File

@ -8,7 +8,7 @@ export default function ManagerLoginPage() {
// O ideal no futuro é deletar esta página e redirecionar os usuários.
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-50 flex items-center justify-center p-4">
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="w-full max-w-md text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">Área do Gestor</h1>
<p className="text-muted-foreground mb-8">Acesse o sistema médico</p>

View File

@ -31,34 +31,35 @@ export default function EditarPacientePage() {
const [isUploadingAnexo, setIsUploadingAnexo] = useState(false);
const anexoInputRef = useRef<HTMLInputElement | null>(null);
// Tipagem completa do formulário
type FormData = {
nome: string; // full_name
nome: string;
cpf: string;
dataNascimento: string; // birth_date
sexo: string; // sex
dataNascimento: string;
sexo: string;
id?: string;
nomeSocial?: string; // social_name
nomeSocial?: string;
rg?: string;
documentType?: string; // document_type
documentNumber?: string; // document_number
documentType?: string;
documentNumber?: string;
ethnicity?: string;
race?: string;
naturality?: string;
nationality?: string;
profession?: string;
maritalStatus?: string; // marital_status
motherName?: string; // mother_name
motherProfession?: string; // mother_profession
fatherName?: string; // father_name
fatherProfession?: string; // father_profession
guardianName?: string; // guardian_name
guardianCpf?: string; // guardian_cpf
spouseName?: string; // spouse_name
rnInInsurance?: boolean; // rn_in_insurance
legacyCode?: string; // legacy_code
maritalStatus?: string;
motherName?: string;
motherProfession?: string;
fatherName?: string;
fatherProfession?: string;
guardianName?: string;
guardianCpf?: string;
spouseName?: string;
rnInInsurance?: boolean;
legacyCode?: string;
notes?: string;
email?: string;
phoneMobile?: string; // phone_mobile
phoneMobile?: string;
phone1?: string;
phone2?: string;
cep?: string;
@ -82,7 +83,6 @@ export default function EditarPacientePage() {
bloodType?: string;
};
const [formData, setFormData] = useState<FormData>({
nome: "",
cpf: "",
@ -141,7 +141,6 @@ export default function EditarPacientePage() {
async function fetchPatient() {
try {
const res = await patientsService.getById(patientId);
// Map API snake_case/nested to local camelCase form
setFormData({
id: res[0]?.id ?? "",
nome: res[0]?.full_name ?? "",
@ -206,7 +205,6 @@ export default function EditarPacientePage() {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Build API payload (snake_case)
const payload = {
full_name: formData.nome || null,
cpf: formData.cpf || null,
@ -247,39 +245,42 @@ export default function EditarPacientePage() {
return (
<Sidebar>
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="space-y-6 px-2 sm:px-4 pb-20">
{/* --- HEADER RESPONSIVO --- */}
<div className="flex flex-col xl:flex-row gap-6 xl:items-start xl:justify-between">
<div className="flex flex-col sm:flex-row sm:items-center gap-4">
<Link href="/manager/pacientes">
<Button variant="ghost" size="sm">
<Button variant="ghost" size="sm" className="-ml-2">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
<div>
<h1 className="text-2xl font-bold text-gray-900">Editar Paciente</h1>
<p className="text-gray-600">Atualize as informações do paciente</p>
<h1 className="text-xl sm:text-2xl font-bold text-foreground">Editar Paciente</h1>
<p className="text-sm text-muted-foreground">Atualize as informações do paciente</p>
</div>
</div>
{/* Anexos Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Anexos</h2>
<div className="w-full xl:w-auto xl:min-w-[400px] bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Anexos</h2>
<div className="flex items-center gap-3 mb-4">
<input ref={anexoInputRef} type="file" className="hidden" />
<Button type="button" variant="outline" disabled={isUploadingAnexo}>
<Button type="button" variant="outline" size="sm" disabled={isUploadingAnexo} className="w-full sm:w-auto">
<Paperclip className="w-4 h-4 mr-2" /> {isUploadingAnexo ? "Enviando..." : "Adicionar anexo"}
</Button>
</div>
{anexos.length === 0 ? (
<p className="text-sm text-gray-500">Nenhum anexo encontrado.</p>
<p className="text-sm text-muted-foreground">Nenhum anexo encontrado.</p>
) : (
<ul className="divide-y">
<ul className="divide-y divide-border">
{anexos.map((a) => (
<li key={a.id} className="flex items-center justify-between py-2">
<div className="flex items-center gap-2 min-w-0">
<Paperclip className="w-4 h-4 text-gray-500 shrink-0" />
<span className="text-sm text-gray-800 truncate">{a.nome || a.filename || `Anexo ${a.id}`}</span>
<Paperclip className="w-4 h-4 text-muted-foreground shrink-0" />
<span className="text-sm text-foreground truncate">{a.nome || a.filename || `Anexo ${a.id}`}</span>
</div>
<Button type="button" variant="ghost" className="text-red-600">
<Button type="button" variant="ghost" size="sm" className="text-destructive">
<Trash2 className="w-4 h-4 mr-1" /> Remover
</Button>
</li>
@ -289,36 +290,38 @@ export default function EditarPacientePage() {
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-8">
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
<form onSubmit={handleSubmit} className="space-y-6 sm:space-y-8">
{/* --- DADOS PESSOAIS --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Dados Pessoais</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* Photo upload */}
<div className="space-y-2">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
{/* Photo upload Responsivo */}
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-3">
<Label>Foto do paciente</Label>
<div className="flex items-center gap-4">
<div className="w-20 h-20 rounded-full bg-gray-100 overflow-hidden flex items-center justify-center">
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
<div className="w-20 h-20 rounded-full bg-muted overflow-hidden flex items-center justify-center shrink-0 border">
{photoUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
) : (
<span className="text-gray-400 text-sm">Sem foto</span>
<span className="text-muted-foreground text-xs text-center px-2">Sem foto</span>
)}
</div>
<div className="flex gap-2">
<div className="flex flex-wrap gap-2 w-full">
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
<Button type="button" variant="outline" disabled={isUploadingPhoto}>
<Button type="button" variant="outline" size="sm" disabled={isUploadingPhoto} className="flex-1 sm:flex-none">
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
</Button>
{photoUrl && (
<Button type="button" variant="ghost" disabled={isUploadingPhoto}>
<Button type="button" variant="ghost" size="sm" disabled={isUploadingPhoto} className="flex-1 sm:flex-none">
Remover
</Button>
)}
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="nome">Nome *</Label>
<Input id="nome" value={formData.nome} onChange={(e) => handleInputChange("nome", e.target.value)} required />
@ -336,13 +339,13 @@ export default function EditarPacientePage() {
<div className="space-y-2">
<Label>Sexo *</Label>
<div className="flex gap-4">
<div className="flex flex-wrap gap-4 pt-2">
<div className="flex items-center space-x-2">
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Masculino">Masculino</Label>
</div>
<div className="flex items-center space-x-2">
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Feminino">Feminino</Label>
</div>
</div>
@ -353,12 +356,11 @@ export default function EditarPacientePage() {
<Input id="dataNascimento" type="date" value={formData.dataNascimento} onChange={(e) => handleInputChange("dataNascimento", e.target.value)} required />
</div>
{/* Demais campos de select e input */}
<div className="space-y-2">
<Label htmlFor="etnia">Etnia</Label>
<Select value={formData.ethnicity} onValueChange={(value) => handleInputChange("ethnicity", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="branca">Branca</SelectItem>
<SelectItem value="preta">Preta</SelectItem>
@ -372,9 +374,7 @@ export default function EditarPacientePage() {
<div className="space-y-2">
<Label htmlFor="raca">Raça</Label>
<Select value={formData.race} onValueChange={(value) => handleInputChange("race", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="caucasiana">Caucasiana</SelectItem>
<SelectItem value="negroide">Negroide</SelectItem>
@ -391,9 +391,7 @@ export default function EditarPacientePage() {
<div className="space-y-2">
<Label htmlFor="nacionalidade">Nacionalidade</Label>
<Select value={formData.nationality} onValueChange={(value) => handleInputChange("nationality", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="brasileira">Brasileira</SelectItem>
<SelectItem value="estrangeira">Estrangeira</SelectItem>
@ -409,9 +407,7 @@ export default function EditarPacientePage() {
<div className="space-y-2">
<Label htmlFor="estadoCivil">Estado civil</Label>
<Select value={formData.maritalStatus} onValueChange={(value) => handleInputChange("maritalStatus", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="solteiro">Solteiro(a)</SelectItem>
<SelectItem value="casado">Casado(a)</SelectItem>
@ -470,26 +466,22 @@ export default function EditarPacientePage() {
</div>
</div>
{/* Contact Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{/* --- CONTATO --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Contato</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="email">E-mail *</Label>
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} required/>
</div>
<div className="space-y-2">
<Label htmlFor="celular">Celular *</Label>
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required/>
</div>
<div className="space-y-2">
<Label htmlFor="telefone1">Telefone 1</Label>
<Input id="telefone1" value={formData.phone1} onChange={(e) => handleInputChange("phone1", e.target.value)} placeholder="(00) 0000-0000" />
</div>
<div className="space-y-2">
<Label htmlFor="telefone2">Telefone 2</Label>
<Input id="telefone2" value={formData.phone2} onChange={(e) => handleInputChange("phone2", e.target.value)} placeholder="(00) 0000-0000" />
@ -497,47 +489,38 @@ export default function EditarPacientePage() {
</div>
</div>
{/* Address Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* --- ENDEREÇO --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Endereço</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="cep">CEP</Label>
<Input id="cep" value={formData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} placeholder="00000-000" />
</div>
<div className="space-y-2">
<div className="space-y-2 md:col-span-2 lg:col-span-2">
<Label htmlFor="endereco">Endereço</Label>
<Input id="endereco" value={formData.street} onChange={(e) => handleInputChange("street", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numero">Número</Label>
<Input id="numero" value={formData.number} onChange={(e) => handleInputChange("number", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="complemento">Complemento</Label>
<Input id="complemento" value={formData.complement} onChange={(e) => handleInputChange("complement", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="bairro">Bairro</Label>
<Input id="bairro" value={formData.neighborhood} onChange={(e) => handleInputChange("neighborhood", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="cidade">Cidade</Label>
<Input id="cidade" value={formData.city} onChange={(e) => handleInputChange("city", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estado">Estado</Label>
<Select value={formData.state} onValueChange={(value) => handleInputChange("state", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="AC">Acre</SelectItem>
<SelectItem value="AL">Alagoas</SelectItem>
@ -572,17 +555,14 @@ export default function EditarPacientePage() {
</div>
</div>
{/* Medical Information Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Médicas</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{/* --- INFORMAÇÕES MÉDICAS --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Informações Médicas</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="tipoSanguineo">Tipo Sanguíneo</Label>
<Select value={formData.bloodType} onValueChange={(value) => handleInputChange("bloodType", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="A+">A+</SelectItem>
<SelectItem value="A-">A-</SelectItem>
@ -595,40 +575,33 @@ export default function EditarPacientePage() {
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="peso">Peso (kg)</Label>
<Input id="peso" type="number" value={formData.weightKg} onChange={(e) => handleInputChange("weightKg", e.target.value)} placeholder="0.0" />
</div>
<div className="space-y-2">
<Label htmlFor="altura">Altura (m)</Label>
<Input id="altura" type="number" step="0.01" value={formData.heightM} onChange={(e) => handleInputChange("heightM", e.target.value)} placeholder="0.00" />
</div>
<div className="space-y-2">
<Label>IMC</Label>
<Input value={formData.weightKg && formData.heightM ? (Number.parseFloat(formData.weightKg) / Number.parseFloat(formData.heightM) ** 2).toFixed(2) : ""} disabled placeholder="Calculado automaticamente" />
</div>
</div>
<div className="mt-6">
<Label htmlFor="alergias">Alergias</Label>
<Textarea id="alergias" onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
</div>
</div>
{/* Insurance Information Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações de convênio</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{/* --- CONVÊNIO --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Informações de convênio</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="convenio">Convênio</Label>
<Select onValueChange={(value) => handleInputChange("convenio", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="Particular">Particular</SelectItem>
<SelectItem value="SUS">SUS</SelectItem>
@ -638,23 +611,19 @@ export default function EditarPacientePage() {
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="plano">Plano</Label>
<Input id="plano" onChange={(e) => handleInputChange("plano", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numeroMatricula"> de matrícula</Label>
<Input id="numeroMatricula" onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
<Input id="validadeCarteira" type="date" onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
</div>
</div>
<div className="mt-4">
<div className="flex items-center space-x-2">
<Checkbox id="validadeIndeterminada" checked={validadeIndeterminada} onCheckedChange={(checked) => setValidadeIndeterminada(checked === true)} />
@ -663,13 +632,14 @@ export default function EditarPacientePage() {
</div>
</div>
<div className="flex justify-end gap-4">
<Link href="/manager/pacientes">
<Button type="button" variant="outline">
{/* --- BOTÕES DE AÇÃO --- */}
<div className="flex flex-col-reverse sm:flex-row justify-end gap-4 pt-4">
<Link href="/manager/pacientes" className="w-full sm:w-auto">
<Button type="button" variant="outline" className="w-full">
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-blue-600 hover:bg-blue-700">
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
<Save className="w-4 h-4 mr-2" />
Salvar Alterações
</Button>

View File

@ -5,55 +5,67 @@ import Link from "next/link";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical, Phone, MapPin, Activity, ChevronLeft, ChevronRight } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { patientsService } from "@/services/patientsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function PacientesPage() {
// --- ESTADOS DE DADOS E GERAL ---
// --- ESTADOS ---
const [searchTerm, setSearchTerm] = useState("");
const [convenioFilter, setConvenioFilter] = useState("all");
const [vipFilter, setVipFilter] = useState("all");
// Lista completa, carregada da API uma única vez
const [allPatients, setAllPatients] = useState<any[]>([]);
// Lista após a aplicação dos filtros (base para a paginação)
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// --- ESTADOS DE PAGINAÇÃO ---
// --- PAGINAÇÃO ---
const [page, setPage] = useState(1);
// PADRONIZAÇÃO: Iniciar com 10 itens por página
const [pageSize, setPageSize] = useState(10);
// CÁLCULO DA PAGINAÇÃO
const totalPages = Math.ceil(filteredPatients.length / pageSize);
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
// Pacientes a serem exibidos na tabela (aplicando a paginação)
const currentPatients = filteredPatients.slice(startIndex, endIndex);
// --- ESTADOS DE DIALOGS ---
// --- DIALOGS ---
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [patientDetails, setPatientDetails] = useState<any | null>(null);
// --- FUNÇÕES DE LÓGICA ---
// --- LÓGICA DE NÚMEROS DA PAGINAÇÃO (LIMITADO A 3) ---
const getPageNumbers = () => {
const maxVisible = 3;
// 1. Função para carregar TODOS os pacientes da API
const fetchAllPacientes = useCallback(
async () => {
if (totalPages <= maxVisible) {
return Array.from({ length: totalPages }, (_, i) => i + 1);
}
let start = Math.max(1, page - 1);
let end = Math.min(totalPages, start + maxVisible - 1);
if (end === totalPages) {
start = Math.max(1, end - maxVisible + 1);
}
const pages = [];
for (let i = start; i <= end; i++) {
pages.push(i);
}
return pages;
};
// --- FETCH DADOS ---
const fetchAllPacientes = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await patientsService.list();
const mapped = res.map((p: any) => ({
id: String(p.id ?? ""),
nome: p.full_name ?? "—",
@ -66,7 +78,6 @@ export default function PacientesPage() {
convenio: p.convenio ?? "Particular",
status: p.status ?? undefined,
}));
setAllPatients(mapped);
} catch (e: any) {
console.error(e);
@ -76,37 +87,22 @@ export default function PacientesPage() {
}
}, []);
// 2. Efeito para aplicar filtros
useEffect(() => {
const filtered = allPatients.filter((patient) => {
const matchesSearch =
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
patient.telefone?.includes(searchTerm);
const matchesConvenio =
convenioFilter === "all" ||
patient.convenio === convenioFilter;
const matchesVip =
vipFilter === "all" ||
(vipFilter === "vip" && patient.vip) ||
(vipFilter === "regular" && !patient.vip);
const matchesSearch = patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) || patient.telefone?.includes(searchTerm);
const matchesConvenio = convenioFilter === "all" || patient.convenio === convenioFilter;
const matchesVip = vipFilter === "all" || (vipFilter === "vip" && patient.vip) || (vipFilter === "regular" && !patient.vip);
return matchesSearch && matchesConvenio && matchesVip;
});
setFilteredPatients(filtered);
setPage(1); // Reseta a página ao filtrar
setPage(1);
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
// 3. Efeito inicial
useEffect(() => {
fetchAllPacientes();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// --- LÓGICA DE AÇÕES ---
// --- AÇÕES ---
const openDetailsDialog = async (patientId: string) => {
setDetailsDialogOpen(true);
setPatientDetails(null);
@ -121,9 +117,7 @@ export default function PacientesPage() {
const handleDeletePatient = async (patientId: string) => {
try {
await patientsService.delete(patientId);
setAllPatients((prev) =>
prev.filter((p) => String(p.id) !== String(patientId))
);
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
} catch (e: any) {
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
}
@ -131,335 +125,211 @@ export default function PacientesPage() {
setPatientToDelete(null);
};
const openDeleteDialog = (patientId: string) => {
setPatientToDelete(patientId);
setDeleteDialogOpen(true);
};
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-8">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h1 className="text-xl md:text-2xl font-bold text-foreground">
Pacientes
</h1>
<p className="text-muted-foreground text-sm md:text-base">
Gerencie as informações de seus pacientes
</p>
</div>
</div>
{/* Filtros */}
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
<Filter className="w-5 h-5 text-gray-400" />
{/* Busca */}
<input
type="text"
placeholder="Buscar por nome ou telefone..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm"
/>
{/* Convênio */}
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
Convênio
</span>
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
<SelectTrigger className="w-full sm:w-40">
<SelectValue placeholder="Convênio" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="Particular">Particular</SelectItem>
<SelectItem value="SUS">SUS</SelectItem>
<SelectItem value="Unimed">Unimed</SelectItem>
</SelectContent>
</Select>
</div>
{/* VIP */}
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
<Select value={vipFilter} onValueChange={setVipFilter}>
<SelectTrigger className="w-full sm:w-32">
<SelectValue placeholder="VIP" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="vip">VIP</SelectItem>
<SelectItem value="regular">Regular</SelectItem>
</SelectContent>
</Select>
</div>
{/* Seletor de Itens por Página (Inicia com 10) */}
<div className="flex items-center gap-2 w-full sm:w-auto ml-auto sm:ml-0">
<Select
value={String(pageSize)}
onValueChange={(value) => {
setPageSize(Number(value));
setPage(1); // Resetar para página 1 ao mudar o tamanho
}}
>
<SelectTrigger className="w-full sm:w-[70px]">
<SelectValue placeholder="10" />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Tabela */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
<div className="overflow-x-auto">
{error ? (
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
Carregando pacientes...
</div>
) : (
<table className="w-full min-w-[650px]">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
</tr>
</thead>
<tbody>
{currentPatients.length === 0 ? (
<tr>
<td colSpan={7} className="p-8 text-center text-gray-500">
{allPatients.length === 0
? "Nenhum paciente cadastrado"
: "Nenhum paciente encontrado com os filtros aplicados"}
</td>
</tr>
) : (
currentPatients.map((patient) => (
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
<td className="p-4">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-blue-600 font-medium text-sm">
{patient.nome?.charAt(0) || "?"}
</span>
</div>
<span className="font-medium text-gray-900">
{patient.nome}
{patient.vip && (
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
VIP
</span>
)}
</span>
</div>
</td>
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
<td className="p-4">
const ActionMenu = ({ patientId }: { patientId: string }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="text-black-600 cursor-pointer">
<div className="cursor-pointer p-2 hover:bg-muted rounded-full">
<MoreVertical className="h-4 w-4" />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
<Eye className="w-4 h-4 mr-2" />
Ver detalhes
<DropdownMenuItem onClick={() => openDetailsDialog(String(patientId))}>
<Eye className="w-4 h-4 mr-2" /> Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
<Edit className="w-4 h-4 mr-2" />
Editar
<Link href={`/manager/pacientes/${patientId}/editar`} className="flex items-center w-full">
<Edit className="w-4 h-4 mr-2" /> Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Calendar className="w-4 h-4 mr-2" />
Marcar consulta
<Calendar className="w-4 h-4 mr-2" /> Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
<Trash2 className="w-4 h-4 mr-2" />
Excluir
<DropdownMenuItem className="text-destructive" onClick={() => { setPatientToDelete(patientId); setDeleteDialogOpen(true); }}>
<Trash2 className="w-4 h-4 mr-2" /> Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-8 pb-20">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h1 className="text-xl md:text-2xl font-bold">Pacientes</h1>
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
</div>
</div>
{/* Filtros */}
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border">
<Filter className="w-5 h-5 text-muted-foreground" />
<input type="text" placeholder="Buscar por nome ou telefone..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm" />
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">Convênio</span>
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
<SelectTrigger className="w-full sm:w-40"><SelectValue placeholder="Convênio" /></SelectTrigger>
<SelectContent><SelectItem value="all">Todos</SelectItem><SelectItem value="Particular">Particular</SelectItem><SelectItem value="SUS">SUS</SelectItem><SelectItem value="Unimed">Unimed</SelectItem></SelectContent>
</Select>
</div>
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">VIP</span>
<Select value={vipFilter} onValueChange={setVipFilter}>
<SelectTrigger className="w-full sm:w-32"><SelectValue placeholder="VIP" /></SelectTrigger>
<SelectContent><SelectItem value="all">Todos</SelectItem><SelectItem value="vip">VIP</SelectItem><SelectItem value="regular">Regular</SelectItem></SelectContent>
</Select>
</div>
<div className="flex items-center gap-2 w-full sm:w-auto ml-auto sm:ml-0">
<Select value={String(pageSize)} onValueChange={(value) => { setPageSize(Number(value)); setPage(1); }}>
<SelectTrigger className="w-full sm:w-[70px]"><SelectValue placeholder="10" /></SelectTrigger>
<SelectContent><SelectItem value="5">5</SelectItem><SelectItem value="10">10</SelectItem><SelectItem value="20">20</SelectItem></SelectContent>
</Select>
</div>
</div>
{/* Loading / Erro / Conteúdo */}
{error ? (
<div className="p-6 text-destructive bg-card border rounded-lg">{`Erro: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-muted-foreground flex items-center justify-center bg-card border rounded-lg"><Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" /> Carregando...</div>
) : (
<>
{/* LISTA MOBILE */}
<div className="grid grid-cols-1 gap-4 md:hidden">
{currentPatients.length === 0 ? (
<div className="p-8 text-center text-muted-foreground bg-card rounded-lg border">Nenhum paciente encontrado.</div>
) : (
currentPatients.map((patient) => (
<div key={patient.id} className="bg-card p-4 rounded-lg border shadow-sm flex flex-col gap-3 relative">
<div className="flex justify-between items-start">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center"><span className="text-primary font-bold text-sm">{patient.nome?.charAt(0) || "?"}</span></div>
<div>
<div className="font-semibold flex items-center gap-2">{patient.nome}{patient.vip && <span className="px-1.5 py-0.5 text-[10px] font-bold rounded-full text-purple-600 bg-purple-100 uppercase">VIP</span>}</div>
<div className="text-xs text-muted-foreground">{patient.convenio}</div>
</div>
</div>
<ActionMenu patientId={String(patient.id)} />
</div>
<div className="grid grid-cols-2 gap-2 text-sm text-muted-foreground mt-2 pt-2 border-t">
<div className="flex items-center gap-2"><Phone className="w-3 h-3" /> {patient.telefone}</div>
<div className="flex items-center gap-2"><MapPin className="w-3 h-3" /> {patient.cidade}</div>
<div className="flex items-center gap-2 col-span-2"><Activity className="w-3 h-3" /> Última: {patient.ultimoAtendimento}</div>
</div>
</div>
))
)}
</div>
{/* TABELA DESKTOP */}
<div className="bg-card rounded-lg border shadow-md hidden md:block">
<div className="overflow-x-auto">
<table className="w-full min-w-[650px]">
<thead className="bg-muted border-b">
<tr>
<th className="text-left p-4 font-medium text-muted-foreground w-[20%]">Nome</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">Telefone</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden md:table-cell">Cidade / Estado</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">Convênio</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">Último atendimento</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">Próximo atendimento</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[5%]">Ações</th>
</tr>
</thead>
<tbody>
{currentPatients.length === 0 ? (
<tr><td colSpan={7} className="p-8 text-center text-muted-foreground">Nenhum paciente encontrado</td></tr>
) : (
currentPatients.map((patient) => (
<tr key={patient.id} className="border-b hover:bg-muted">
<td className="p-4">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center"><span className="text-primary font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span></div>
<span className="font-medium">{patient.nome}{patient.vip && <span className="ml-2 px-2 py-0.5 text-xs font-semibold rounded-full text-purple-400 bg-purple-400/15">VIP</span>}</span>
</div>
</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">{patient.telefone}</td>
<td className="p-4 text-muted-foreground hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">{patient.convenio}</td>
<td className="p-4 text-muted-foreground hidden lg:table-cell">{patient.ultimoAtendimento}</td>
<td className="p-4 text-muted-foreground hidden lg:table-cell">{patient.proximoAtendimento}</td>
<td className="p-4"><ActionMenu patientId={String(patient.id)} /></td>
</tr>
))
)}
</tbody>
</table>
)}
</div>
</div>
</>
)}
{/* --- RODAPÉ DE PAGINAÇÃO --- */}
{totalPages > 1 && !loading && (
<div className="py-4 px-2 border-t border-border">
{/* 1. PAGINAÇÃO MOBILE (Simples) */}
<div className="flex items-center justify-between md:hidden gap-2">
<Button onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page === 1} variant="outline" size="sm" className="min-w-[90px]">
<ChevronLeft className="w-4 h-4 mr-1" /> Anterior
</Button>
<span className="text-sm font-medium text-muted-foreground">{page} de {totalPages}</span>
<Button onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page === totalPages} variant="outline" size="sm" className="min-w-[90px]">
Próximo <ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
{/* Paginação */}
{totalPages > 1 && !loading && (
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
<div className="flex space-x-2 flex-wrap justify-center">
<Button
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
disabled={page === 1}
variant="outline"
size="lg"
>
{/* 2. PAGINAÇÃO DESKTOP (Numerada Limitada) */}
<div className="hidden md:flex items-center justify-center gap-2">
<Button onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page === 1} variant="outline" className="px-4">
&lt; Anterior
</Button>
{Array.from({ length: totalPages }, (_, index) => index + 1)
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
.map((pageNumber) => (
{getPageNumbers().map((pageNum) => (
<Button
key={pageNumber}
onClick={() => setPage(pageNumber)}
variant={pageNumber === page ? "default" : "outline"}
size="lg"
className={
pageNumber === page
? "bg-blue-600 hover:bg-blue-700 text-white"
: "text-gray-700"
}
key={pageNum}
onClick={() => setPage(pageNum)}
/* CORREÇÃO AQUI: Removemos as classes manuais e usamos apenas o variant */
variant={pageNum === page ? "default" : "outline"}
className="w-10 h-10 p-0"
>
{pageNumber}
{pageNum}
</Button>
))}
<Button
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
disabled={page === totalPages}
variant="outline"
size="lg"
>
<Button onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page === totalPages} variant="outline" className="px-4">
Próximo &gt;
</Button>
</div>
</div>
)}
{/* Dialog de Exclusão */}
{/* Dialogs */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
<AlertDialogDescription>
Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction
onClick={() => patientToDelete && handleDeletePatient(patientToDelete)}
className="bg-red-600 hover:bg-red-700"
>
Excluir
</AlertDialogAction>
</AlertDialogFooter>
<AlertDialogHeader><AlertDialogTitle>Confirmar exclusão</AlertDialogTitle><AlertDialogDescription>Tem certeza que deseja excluir este paciente?</AlertDialogDescription></AlertDialogHeader>
<AlertDialogFooter><AlertDialogCancel>Cancelar</AlertDialogCancel><AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-destructive hover:bg-destructive/90">Excluir</AlertDialogAction></AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Dialog de Detalhes */}
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
<AlertDialogContent className="max-h-[90vh] overflow-y-auto">
<AlertDialogHeader><AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle></AlertDialogHeader>
<AlertDialogDescription>
{patientDetails === null ? (
<div className="text-gray-500">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
Carregando...
</div>
) : patientDetails?.error ? (
<div className="text-red-600 p-4">{patientDetails.error}</div>
) : (
<div className="grid gap-4 py-4">
{patientDetails ? (!patientDetails.error ? (
<div className="grid gap-4 py-4 text-left">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<p className="font-semibold">Nome Completo</p>
<p>{patientDetails.full_name}</p>
<div><p className="font-semibold text-xs text-muted-foreground">NOME</p><p>{patientDetails.full_name}</p></div>
<div><p className="font-semibold text-xs text-muted-foreground">EMAIL</p><p className="break-all">{patientDetails.email}</p></div>
<div><p className="font-semibold text-xs text-muted-foreground">TELEFONE</p><p>{patientDetails.phone_mobile}</p></div>
<div><p className="font-semibold text-xs text-muted-foreground">DATA NASC.</p><p>{patientDetails.birth_date}</p></div>
</div>
<div>
<p className="font-semibold">Email</p>
<p>{patientDetails.email}</p>
<div className="border-t pt-4"><p className="font-semibold text-primary mb-2">Endereço</p><p>{patientDetails.street}, {patientDetails.number}</p><p>{patientDetails.cidade}/{patientDetails.estado}</p></div>
</div>
<div>
<p className="font-semibold">Telefone</p>
<p>{patientDetails.phone_mobile}</p>
</div>
<div>
<p className="font-semibold">Data de Nascimento</p>
<p>{patientDetails.birth_date}</p>
</div>
<div>
<p className="font-semibold">CPF</p>
<p>{patientDetails.cpf}</p>
</div>
<div>
<p className="font-semibold">Tipo Sanguíneo</p>
<p>{patientDetails.blood_type}</p>
</div>
<div>
<p className="font-semibold">Peso (kg)</p>
<p>{patientDetails.weight_kg}</p>
</div>
<div>
<p className="font-semibold">Altura (m)</p>
<p>{patientDetails.height_m}</p>
</div>
</div>
<div className="border-t pt-4 mt-4">
<h3 className="font-semibold mb-2">Endereço</h3>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<p className="font-semibold">Rua</p>
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
</div>
<div>
<p className="font-semibold">Complemento</p>
<p>{patientDetails.complement}</p>
</div>
<div>
<p className="font-semibold">Bairro</p>
<p>{patientDetails.neighborhood}</p>
</div>
<div>
<p className="font-semibold">Cidade</p>
<p>{patientDetails.cidade}</p>
</div>
<div>
<p className="font-semibold">Estado</p>
<p>{patientDetails.estado}</p>
</div>
<div>
<p className="font-semibold">CEP</p>
<p>{patientDetails.cep}</p>
</div>
</div>
</div>
</div>
)}
) : <p className="text-destructive">{patientDetails.error}</p>) : <Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Fechar</AlertDialogCancel>
</AlertDialogFooter>
<AlertDialogFooter><AlertDialogCancel>Fechar</AlertDialogCancel></AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>

View File

@ -157,8 +157,8 @@ export default function EditarUsuarioPage() {
return (
<Sidebar>
<div className="flex justify-center items-center h-full w-full py-16">
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
<p className="ml-2 text-gray-600">Carregando dados do usuário...</p>
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="ml-2 text-muted-foreground">Carregando dados do usuário...</p>
</div>
</Sidebar>
);
@ -169,10 +169,10 @@ export default function EditarUsuarioPage() {
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">
Editar Usuário: <span className="text-green-600">{formData.nomeCompleto}</span>
<h1 className="text-2xl font-bold text-foreground">
Editar Usuário: <span className="text-primary">{formData.nomeCompleto}</span>
</h1>
<p className="text-sm text-gray-500">
<p className="text-sm text-muted-foreground">
Atualize as informações do usuário (ID: {id}).
</p>
</div>
@ -184,9 +184,9 @@ export default function EditarUsuarioPage() {
</Link>
</div>
<form onSubmit={handleSubmit} className="space-y-8 bg-white p-8 border rounded-lg shadow-sm">
<form onSubmit={handleSubmit} className="space-y-8 bg-card p-8 border border-border rounded-lg shadow-sm">
{error && (
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
<div className="p-3 rounded-lg border bg-destructive/10 text-destructive border-destructive/30">
<p className="font-medium">Erro na Atualização:</p>
<p className="text-sm">{error}</p>
</div>
@ -261,7 +261,7 @@ export default function EditarUsuarioPage() {
</Link>
<Button
type="submit"
className="bg-green-600 hover:bg-green-700"
className="bg-primary hover:bg-primary/90"
disabled={isSaving}
>
{isSaving ? (

View File

@ -140,17 +140,17 @@ export default function NovoUsuarioPage() {
<div className="w-full max-w-screen-lg space-y-8">
<div className="flex items-center justify-between border-b pb-4">
<div>
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
<p className="text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p>
<h1 className="text-3xl font-extrabold">Novo Usuário</h1>
<p className="text-md text-muted-foreground">Preencha os dados para cadastrar um novo usuário no sistema.</p>
</div>
<Link href="/manager/usuario">
<Button variant="outline">Cancelar</Button>
</Link>
</div>
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
<form onSubmit={handleSubmit} className="space-y-6 bg-card p-6 md:p-10 border rounded-xl shadow-lg">
{error && (
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
<div className="p-4 bg-destructive/10 text-destructive rounded-lg border border-destructive">
<p className="font-semibold">Erro no Cadastro:</p>
<p className="text-sm break-words">{error}</p>
</div>
@ -208,7 +208,7 @@ export default function NovoUsuarioPage() {
<div className="space-y-2">
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-destructive">As senhas não coincidem.</p>}
</div>
<div className="space-y-2">
@ -228,7 +228,7 @@ export default function NovoUsuarioPage() {
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-green-600 hover:bg-green-700" disabled={isSaving}>
<Button type="submit" className="bg-primary hover:bg-primary/90" disabled={isSaving}>
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
{isSaving ? "Salvando..." : "Salvar Usuário"}
</Button>

View File

@ -182,22 +182,22 @@ export default function UsersPage() {
{/* Header */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
<p className="text-sm text-gray-500">Gerencie usuários.</p>
<h1 className="text-2xl font-bold">Usuários</h1>
<p className="text-sm text-muted-foreground">Gerencie usuários.</p>
</div>
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
<Button className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700">
<Button className="w-full sm:w-auto">
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
</Button>
</Link>
</div>
{/* --- 4. Filtro (Barra de Pesquisa + Selects) --- */}
<div className="flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
<div className="flex flex-col md:flex-row items-start md:items-center gap-3 bg-card p-4 rounded-lg border">
{/* Barra de Pesquisa */}
<div className="relative w-full md:flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Buscar por nome, e-mail ou telefone..."
value={searchTerm}
@ -205,7 +205,7 @@ export default function UsersPage() {
setSearchTerm(e.target.value);
setCurrentPage(1); // Reseta a paginação ao pesquisar
}}
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
className="pl-10 w-full bg-muted border-border focus:bg-card transition-colors"
/>
</div>
@ -259,54 +259,54 @@ export default function UsersPage() {
{/* Fim do Filtro */}
{/* Tabela/Lista */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
<div className="bg-card rounded-lg border shadow-md overflow-x-auto">
{loading ? (
<div className="p-8 text-center text-gray-500">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
<div className="p-8 text-center text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
Carregando usuários...
</div>
) : error ? (
<div className="p-8 text-center text-red-600">{error}</div>
<div className="p-8 text-center text-destructive">{error}</div>
) : filteredUsers.length === 0 ? (
<div className="p-8 text-center text-gray-500">
<div className="p-8 text-center text-muted-foreground">
Nenhum usuário encontrado com os filtros aplicados.
</div>
) : (
<>
{/* Tabela para Telas Médias e Grandes */}
<table className="min-w-full divide-y divide-gray-200 hidden md:table">
<thead className="bg-gray-50">
<table className="min-w-full divide-y hidden md:table">
<thead className="bg-muted">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
Nome
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
E-mail
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
Telefone
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
Cargo
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
<th className="px-6 py-3 text-right text-xs font-medium text-muted-foreground uppercase">
Ações
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
<tbody className="bg-card divide-y">
{currentItems.map((u) => (
<tr key={u.id} className="hover:bg-gray-50">
<td className="px-6 py-4 text-sm text-gray-900">
<tr key={u.id} className="hover:bg-muted">
<td className="px-6 py-4 text-sm">
{u.full_name}
</td>
<td className="px-6 py-4 text-sm text-gray-500 break-all">
<td className="px-6 py-4 text-sm text-muted-foreground break-all">
{u.email}
</td>
<td className="px-6 py-4 text-sm text-gray-500">
<td className="px-6 py-4 text-sm text-muted-foreground">
{u.phone}
</td>
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
<td className="px-6 py-4 text-sm text-muted-foreground capitalize">
{u.role}
</td>
<td className="px-6 py-4 text-right">
@ -325,17 +325,17 @@ export default function UsersPage() {
</table>
{/* Layout em Cards/Lista para Telas Pequenas */}
<div className="md:hidden divide-y divide-gray-200">
<div className="md:hidden divide-y">
{currentItems.map((u) => (
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-gray-50">
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-muted">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 truncate">
<div className="text-sm font-medium truncate">
{u.full_name || "—"}
</div>
<div className="text-xs text-gray-500 truncate">
<div className="text-xs text-muted-foreground truncate">
{u.email}
</div>
<div className="text-sm text-gray-500 capitalize mt-1">
<div className="text-sm text-muted-foreground capitalize mt-1">
{u.role || "—"}
</div>
</div>
@ -355,12 +355,12 @@ export default function UsersPage() {
{/* Paginação */}
{totalPages > 1 && (
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t">
{/* Botão Anterior */}
<button
onClick={goToPrevPage}
disabled={currentPage === 1}
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"< Anterior"}
</button>
@ -370,10 +370,10 @@ export default function UsersPage() {
<button
key={number}
onClick={() => paginate(number)}
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border ${
currentPage === number
? "bg-blue-600 text-white shadow-md border-blue-600"
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
? "bg-primary text-primary-foreground shadow-md border-primary"
: "bg-muted text-muted-foreground hover:bg-muted/90"
}`}
>
{number}
@ -384,7 +384,7 @@ export default function UsersPage() {
<button
onClick={goToNextPage}
disabled={currentPage === totalPages}
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"Próximo >"}
</button>
@ -406,12 +406,12 @@ export default function UsersPage() {
</AlertDialogTitle>
<AlertDialogDescription>
{!userDetails ? (
<div className="p-4 text-center text-gray-500">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
<div className="p-4 text-center text-muted-foreground">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-primary" />
Buscando dados completos...
</div>
) : (
<div className="space-y-3 pt-2 text-left text-gray-700">
<div className="space-y-3 pt-2 text-left text-muted-foreground">
<div>
<strong>ID:</strong> {userDetails.user.id}
</div>
@ -437,7 +437,7 @@ export default function UsersPage() {
{k}:{" "}
<span
className={`font-semibold ${
v ? "text-green-600" : "text-red-600"
v ? "text-primary" : "text-destructive"
}`}
>
{v ? "Sim" : "Não"}

View File

@ -4,28 +4,34 @@ import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { Stethoscope, Baby, Microscope } from "lucide-react";
import { useAccessibility } from "./context/AccessibilityContext";
export default function InicialPage() {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { contrast } = useAccessibility();
const heroClass = contrast === "high"
? "px-6 md:px-10 lg:px-20 py-20 bg-background text-foreground border-y-2 border-primary"
: "px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white";
return (
<div className="min-h-screen flex flex-col bg-white font-sans scroll-smooth text-[#1E2A78]">
<div className="min-h-screen flex flex-col bg-background font-sans scroll-smooth text-foreground">
{/* Barra superior */}
<div className="bg-[#1E2A78] text-white text-sm py-2 px-4 md:px-6 flex justify-between items-center">
<div className="bg-primary text-primary-foreground text-sm py-2 px-4 md:px-6 flex justify-between items-center">
<span className="hidden sm:inline">Horário: 08h00 - 21h00</span>
<span className="hover:underline cursor-pointer transition">
Email: contato@mediconnect.com
</span>
</div>
{/* Header */}
<header className="bg-white shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
<header className="bg-muted text-foreground shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
<a href="#home" className="flex items-center space-x-2 cursor-pointer">
<img
src="/android-chrome-512x512.png"
alt="Logo MediConnect"
className="w-20 h-20 object-contain transition-transform hover:scale-105"
/>
<h1 className="text-2xl font-extrabold text-[#1E2A78] tracking-tight">
<h1 className="text-2xl font-extrabold text-foreground tracking-tight">
MedConnect
</h1>
</a>
@ -35,7 +41,7 @@ export default function InicialPage() {
<Link href="/login">
<Button
variant="outline"
className="rounded-full px-4 py-2 text-sm border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition"
className="rounded-full px-4 py-2 text-sm border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground transition"
>
Login
</Button>
@ -76,20 +82,20 @@ export default function InicialPage() {
isMenuOpen ? "block" : "hidden"
} absolute top-[76px] left-0 w-full bg-white shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none transition-all duration-300 z-10`}
>
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-gray-600 font-medium items-center">
<Link href="#home" className="hover:text-[#007BFF] transition">
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-foreground font-medium items-center">
<Link href="#home" className="hover:text-primary transition">
Home
</Link>
<a href="#about" className="hover:text-[#007BFF] transition">
<a href="#about" className="hover:text-primary transition">
Sobre
</a>
<a href="#departments" className="hover:text-[#007BFF] transition">
<a href="#departments" className="hover:text-primary transition">
Departamentos
</a>
<a href="#doctors" className="hover:text-[#007BFF] transition">
<a href="#doctors" className="hover:text-primary transition">
Médicos
</a>
<a href="#contact" className="hover:text-[#007BFF] transition">
<a href="#contact" className="hover:text-primary transition">
Contato
</a>
</div>
@ -100,7 +106,7 @@ export default function InicialPage() {
<Link href="/login">
<Button
variant="outline"
className="rounded-full px-6 py-2 border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition cursor-pointer"
className="rounded-full px-6 py-2 border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground transition cursor-pointer"
>
Login
</Button>
@ -108,7 +114,7 @@ export default function InicialPage() {
</div>
</header>
{/* Hero Section */}
<section className="flex flex-col md:flex-row items-center justify-between px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white">
<section className={`flex flex-col md:flex-row items-center justify-between ${heroClass}`}>
<div className="max-w-lg mx-auto md:mx-0">
<h2 className="uppercase text-sm tracking-widest opacity-80">
Bem-vindo à Saúde Digital
@ -116,15 +122,15 @@ export default function InicialPage() {
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-tight mt-2 drop-shadow-lg">
Soluções Médicas <br /> & Cuidados com a Saúde
</h1>
<p className="mt-4 text-base leading-relaxed opacity-90">
<p className="mt-4 text-base leading-relaxed opacity-90 text-foreground">
Excelência em saúde mais de 25 anos. Atendimento médico com
qualidade, segurança e carinho.
</p>
<div className="mt-8 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
<Button className="px-8 py-3 text-base font-semibold bg-card text-card-foreground hover:bg-muted transition-all shadow-md">
Nossos Serviços
</Button>
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
<Button className="px-8 py-3 text-base font-semibold bg-card text-card-foreground hover:bg-muted transition-all shadow-md">
Saiba Mais
</Button>
</div>
@ -140,12 +146,12 @@ export default function InicialPage() {
{/* Serviços */}
<section
id="departments"
className="py-20 px-6 md:px-10 lg:px-20 bg-[#F8FBFF]"
className="py-20 px-6 md:px-10 lg:px-20 bg-secondary"
>
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-[#1E2A78]">
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-foreground">
Cuidados completos para a sua saúde
</h2>
<p className="text-center text-gray-600 mt-3 text-base">
<p className="text-center text-muted-foreground mt-3 text-base">
Serviços médicos que oferecemos
</p>
@ -170,16 +176,16 @@ export default function InicialPage() {
].map(({ title, desc, Icon }, index) => (
<div
key={index}
className="p-8 bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-[#E0E9FF] group"
className="p-8 bg-card rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-border group"
>
<div className="flex items-center space-x-3">
<Icon className="text-[#007BFF] w-6 h-6 group-hover:scale-110 transition-transform" />
<Icon className="text-primary w-6 h-6 group-hover:scale-110 transition-transform" />
<h3 className="text-xl font-semibold">{title}</h3>
</div>
<p className="text-gray-600 mt-3 text-sm leading-relaxed">
<p className="text-muted-foreground mt-3 text-sm leading-relaxed">
{desc}
</p>
<Button className="mt-6 w-full bg-[#007BFF] hover:bg-[#005FCC] text-white transition">
<Button className="mt-6 w-full bg-primary hover:opacity-90 text-primary-foreground transition">
Agendar
</Button>
</div>
@ -187,17 +193,17 @@ export default function InicialPage() {
</div>
</section>
{/* Footer */}
<footer className="bg-[#1E2A78] text-white py-8 text-center text-sm">
<footer className="bg-primary text-primary-foreground py-8 text-center text-sm border-t-2 border-primary-foreground/20">
<div className="space-y-2">
<p>© 2025 MediConnect Todos os direitos reservados</p>
<div className="flex justify-center space-x-6 opacity-80">
<a href="#about" className="hover:text-[#00BFFF] transition">
<div className="flex justify-center space-x-6 opacity-90">
<a href="#about" className="hover:opacity-70 transition">
Sobre
</a>
<a href="#departments" className="hover:text-[#00BFFF] transition">
<a href="#departments" className="hover:opacity-70 transition">
Serviços
</a>
<a href="#contact" className="hover:text-[#00BFFF] transition">
<a href="#contact" className="hover:opacity-70 transition">
Contato
</a>
</div>

View File

@ -1,93 +1,83 @@
"use client";
import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Calendar, Clock, CalendarDays, X } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Calendar,
Clock,
MapPin,
Phone,
User,
X,
AlertCircle,
} from "lucide-react";
import { toast } from "sonner";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { usersService } from "@/services/usersApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar";
// Tipagem correta para o usuário
interface UserProfile {
id: string;
full_name: string;
email: string;
phone?: string;
avatar_url?: string;
}
interface User {
user: {
id: string;
email: string;
};
profile: UserProfile;
roles: string[];
permissions?: any;
}
interface Appointment {
id: string;
doctor_id: string;
scheduled_at: string;
status: string;
doctorName?: string;
}
export default function PatientAppointmentsPage() {
const [appointments, setAppointments] = useState<Appointment[]>([]);
const [appointments, setAppointments] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [userData, setUserData] = useState<User | null>(null);
// --- Busca o usuário logado ---
const fetchUser = async () => {
try {
const user: User = await usersService.getMe();
if (!user.roles.includes("patient") && !user.roles.includes("user")) {
toast.error("Apenas pacientes podem visualizar suas consultas.");
setIsLoading(false);
return null;
}
setUserData(user);
return user;
} catch (err) {
console.error("Erro ao buscar usuário logado:", err);
toast.error("Não foi possível identificar o usuário logado.");
setIsLoading(false);
return null;
}
};
// Estados para cancelamento
const [cancelModal, setCancelModal] = useState(false);
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
// --- Busca consultas do paciente ---
const fetchAppointments = async (patientId: string) => {
const fetchData = async () => {
setIsLoading(true);
try {
const queryParams = `patient_id=eq.${patientId}&order=scheduled_at.desc`;
const appointmentsList: Appointment[] = await appointmentsService.search_appointment(queryParams);
// Buscar nome do médico para cada consulta
const appointmentsWithDoctor = await Promise.all(
appointmentsList.map(async (apt) => {
let doctorName = apt.doctor_id;
if (apt.doctor_id) {
try {
const doctorInfo = await usersService.full_data(apt.doctor_id);
doctorName = doctorInfo?.profile?.full_name || apt.doctor_id;
} catch (err) {
console.error("Erro ao buscar nome do médico:", err);
// 1. Obter usuário logado
const user = await usersService.getMe();
if (!user || !user.user?.id) {
toast.error("Usuário não identificado.");
return;
}
}
return { ...apt, doctorName };
})
);
setAppointments(appointmentsWithDoctor);
} catch (err) {
console.error("Erro ao carregar consultas:", err);
// 2. Buscar médicos e agendamentos em paralelo
// Filtra apenas agendamentos deste paciente
const queryParams = `patient_id=eq.${"user.user.id"}&order=scheduled_at.desc`;
console.log("id do paciente:", user.profile.id);
const [appointmentList, doctorList] = await Promise.all([
appointmentsService.search_appointment(queryParams),
doctorsService.list(),
]);
console.log("Agendamentos obtidos:", appointmentList);
console.log("Médicos obtidos:", doctorList);
// 3. Mapear médicos para acesso rápido
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
// 4. Enriquecer os agendamentos com dados do médico
const enrichedAppointments = appointmentList.map((apt: any) => ({
...apt,
doctor: doctorMap.get(apt.doctor_id) || {
full_name: "Médico não encontrado",
specialty: "Clínico Geral",
location: "Consultório",
phone: "N/A"
},
}));
console.log("Agendamentos enriquecidos:", enrichedAppointments);
setAppointments(enrichedAppointments);
} catch (error) {
console.error("Erro ao buscar dados:", error);
toast.error("Não foi possível carregar suas consultas.");
} finally {
setIsLoading(false);
@ -95,96 +85,187 @@ export default function PatientAppointmentsPage() {
};
useEffect(() => {
(async () => {
const user = await fetchUser();
if (user?.user.id) {
await fetchAppointments(user.user.id);
}
})();
fetchData();
}, []);
const getStatusBadge = (status: string) => {
switch (status) {
case "requested":
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
case "confirmed":
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
case "checked_in":
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
case "completed":
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
case "cancelled":
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
default:
return <Badge variant="secondary">{status}</Badge>;
// --- LÓGICA DE CANCELAMENTO ---
const handleCancelClick = (appointment: any) => {
setSelectedAppointment(appointment);
setCancelModal(true);
};
const confirmCancel = async () => {
if (!selectedAppointment) return;
try {
// Opção A: Deletar o registro (como no código da secretária)
await appointmentsService.delete(selectedAppointment.id);
// Opção B: Se preferir apenas mudar o status, descomente abaixo e comente a linha acima:
// await appointmentsService.update(selectedAppointment.id, { status: 'cancelled' });
setAppointments((prev) =>
prev.filter((apt) => apt.id !== selectedAppointment.id)
);
setCancelModal(false);
toast.success("Consulta cancelada com sucesso.");
} catch (error) {
console.error("Erro ao cancelar consulta:", error);
toast.error("Não foi possível cancelar a consulta.");
}
};
const handleReschedule = (apt: Appointment) => {
toast.info(`Funcionalidade de reagendamento da consulta ${apt.id} ainda não implementada`);
};
const handleCancel = (apt: Appointment) => {
toast.info(`Funcionalidade de cancelamento da consulta ${apt.id} ainda não implementada`);
};
return (
<Sidebar>
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold text-foreground">Minhas Consultas</h1>
<p className="text-muted-foreground">Veja, reagende ou cancele suas consultas</p>
<h1 className="text-3xl font-bold">Minhas Consultas</h1>
<p className="text-muted-foreground">
Acompanhe seu histórico e próximos agendamentos
</p>
</div>
</div>
<div className="grid gap-6">
{isLoading ? (
<p>Carregando consultas...</p>
) : appointments.length === 0 ? (
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
) : (
appointments.map((apt) => (
<Card key={apt.id}>
<CardHeader className="flex justify-between items-start">
) : appointments.length > 0 ? (
appointments.map((appointment) => (
<Card key={appointment.id}>
<CardHeader>
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-lg">{apt.doctorName}</CardTitle>
<CardDescription>Especialidade: N/A</CardDescription>
<CardTitle className="text-lg">
{appointment.doctor.full_name}
</CardTitle>
<CardDescription>
{appointment.doctor.specialty}
</CardDescription>
</div>
{getStatusBadge(appointment.status)}
</div>
{getStatusBadge(apt.status)}
</CardHeader>
<CardContent className="grid md:grid-cols-2 gap-3 text-sm text-gray-700">
<div className="space-y-2">
<div className="flex items-center">
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
{new Date(apt.scheduled_at).toLocaleDateString("pt-BR")}
<CardContent>
<div className="grid md:grid-cols-2 gap-4">
{/* Coluna 1: Data e Hora */}
<div className="space-y-3">
<div className="flex items-center text-sm text-foreground font-medium">
<User className="mr-2 h-4 w-4 text-muted-foreground" />
Dr(a). {appointment.doctor.full_name.split(' ')[0]}
</div>
<div className="flex items-center">
<Clock className="mr-2 h-4 w-4 text-gray-500" />
{new Date(apt.scheduled_at).toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
})}
</div>
</div>
<div className="flex gap-2 mt-4 pt-4 border-t">
{apt.status !== "cancelled" && (
<>
<Button variant="outline" size="sm" onClick={() => handleReschedule(apt)}>
<CalendarDays className="mr-2 h-4 w-4" /> Reagendar
</Button>
<Button variant="destructive" size="sm" onClick={() => handleCancel(apt)}>
<X className="mr-2 h-4 w-4" /> Cancelar
</Button>
</>
<div className="flex items-center text-sm text-muted-foreground">
<Calendar className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleDateString(
"pt-BR",
{ timeZone: "UTC" }
)}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Clock className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleTimeString(
"pt-BR",
{
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
}
)}
</div>
</div>
{/* Coluna 2: Localização e Contato */}
<div className="space-y-3">
<div className="flex items-center text-sm text-muted-foreground">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Phone className="mr-2 h-4 w-4" />
{appointment.doctor.phone || "Contato não disponível"}
</div>
</div>
</div>
{/* Ações */}
{["requested", "confirmed"].includes(appointment.status) && (
<div className="flex gap-2 mt-4 pt-4 border-t justify-end">
<Button
variant="destructive"
size="sm"
className="bg-transparent text-destructive hover:bg-destructive/10 border border-destructive/20"
onClick={() => handleCancelClick(appointment)}
>
<X className="mr-2 h-4 w-4" />
Cancelar Consulta
</Button>
</div>
)}
</CardContent>
</Card>
))
) : (
<div className="text-center py-10 border rounded-lg bg-muted/20">
<Calendar className="mx-auto h-10 w-10 text-muted-foreground mb-4" />
<p className="text-muted-foreground">Você ainda não possui consultas agendadas.</p>
</div>
)}
</div>
</div>
{/* Modal de Confirmação de Cancelamento */}
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-destructive" />
Cancelar Consulta
</DialogTitle>
<DialogDescription>
Tem certeza que deseja cancelar sua consulta com{" "}
<strong>{selectedAppointment?.doctor?.full_name}</strong> no dia{" "}
{selectedAppointment &&
new Date(selectedAppointment.scheduled_at).toLocaleDateString(
"pt-BR", { timeZone: "UTC" }
)}
? Esta ação não pode ser desfeita.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setCancelModal(false)}>
Voltar
</Button>
<Button variant="destructive" onClick={confirmCancel}>
Confirmar Cancelamento
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</Sidebar>
);
}
// Helper para Badges (Mantido consistente com o código da secretária)
const getStatusBadge = (status: string) => {
switch (status) {
case "requested":
return (
<Badge className="bg-yellow-400/10 text-yellow-600 hover:bg-yellow-400/20 border-yellow-400/20">Solicitada</Badge>
);
case "confirmed":
return <Badge className="bg-primary/10 text-primary hover:bg-primary/20 border-primary/20">Confirmada</Badge>;
case "checked_in":
return (
<Badge className="bg-indigo-400/10 text-indigo-600 hover:bg-indigo-400/20 border-indigo-400/20">Check-in</Badge>
);
case "completed":
return <Badge className="bg-green-400/10 text-green-600 hover:bg-green-400/20 border-green-400/20">Realizada</Badge>;
case "cancelled":
return <Badge className="bg-destructive/10 text-destructive hover:bg-destructive/20 border-destructive/20">Cancelada</Badge>;
case "no_show":
return (
<Badge className="bg-muted text-foreground border-muted-foreground/20">Não Compareceu</Badge>
);
default:
return <Badge variant="secondary">{status}</Badge>;
}
};

View File

@ -15,8 +15,8 @@ export default function PatientDashboard() {
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<p className="text-gray-600">
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
@ -72,15 +72,15 @@ export default function PatientDashboard() {
</CardHeader>
<CardContent className="space-y-4">
<Link href="/patient/schedule">
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
<User className="mr-2 h-4 w-4 text-white" />
<Button className="w-full justify-start">
<User className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link>
<Link href="/patient/appointments">
<Button
variant="outline"
className="w-full justify-start bg-transparent bg-blue-600 hover:bg-blue-700 text-white"
variant="secondary"
className="w-full justify-start"
>
<Calendar className="mr-2 h-4 w-4" />
Ver Minhas Consultas
@ -89,7 +89,7 @@ export default function PatientDashboard() {
<Link href="/patient/profile">
<Button
variant="outline"
className="w-full justify-start bg-transparent"
className="w-full justify-start"
>
<User className="mr-2 h-4 w-4" />
Atualizar Dados
@ -105,24 +105,24 @@ export default function PatientDashboard() {
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
<div>
<p className="font-medium">Dr. Silva</p>
<p className="text-sm text-gray-600">Cardiologia</p>
<p className="text-sm text-muted-foreground">Cardiologia</p>
</div>
<div className="text-right">
<p className="font-medium">15 Jan</p>
<p className="text-sm text-gray-600">14:30</p>
<p className="text-sm text-muted-foreground">14:30</p>
</div>
</div>
<div className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
<div>
<p className="font-medium">Dra. Santos</p>
<p className="text-sm text-gray-600">Dermatologia</p>
<p className="text-sm text-muted-foreground">Dermatologia</p>
</div>
<div className="text-right">
<p className="font-medium">22 Jan</p>
<p className="text-sm text-gray-600">10:00</p>
<p className="text-sm text-muted-foreground">10:00</p>
</div>
</div>
</div>

View File

@ -1,18 +1,17 @@
// ARQUIVO COMPLETO PARA: app/patient/profile/page.tsx
// Caminho: app/patient/profile/page.tsx
"use client";
import { useState, useEffect, useRef } from "react";
import Sidebar from "@/components/Sidebar";
import { useAuthLayout } from "@/hooks/useAuthLayout";
import { patientsService } from "@/services/patientsApi.mjs";
import { usersService } from "@/services/usersApi.mjs"; // Adicionado import
import { api } from "@/services/api.mjs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { User, Mail, Phone, Calendar, Upload } from "lucide-react";
import { toast } from "@/hooks/use-toast";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
@ -34,18 +33,45 @@ export default function PatientProfile() {
const { user, isLoading: isAuthLoading } = useAuthLayout({
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
});
const [patientData, setPatientData] = useState<PatientProfileData | null>(
null
);
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
const [isEditing, setIsEditing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const getInitials = (name: string) => {
if (!name) return "U";
return name
.split(" ")
.map((n) => n[0])
.slice(0, 2)
.join("")
.toUpperCase();
};
// Função auxiliar para construir URL do avatar
const buildAvatarUrl = (path: string | null | undefined) => {
if (!path) return undefined;
const baseUrl = "https://yuanqfswhberkoevtmfr.supabase.co";
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
const separator = cleanPath.includes('?') ? '&' : '?';
return `${baseUrl}/storage/v1/object/avatars/${cleanPath}${separator}t=${new Date().getTime()}`;
};
useEffect(() => {
if (user?.id) {
const fetchPatientDetails = async () => {
const loadData = async () => {
try {
// 1. Busca dados médicos (Tabela Patients)
const patientDetails = await patientsService.getById(user.id);
// 2. Busca dados de sistema frescos (Tabela Profiles via getMe)
// Isso garante que pegamos o avatar real do banco, não do cache local
const userSystemData = await usersService.getMe();
const freshAvatarPath = userSystemData?.profile?.avatar_url;
const freshAvatarUrl = buildAvatarUrl(freshAvatarPath);
setPatientData({
name: patientDetails.full_name || user.name,
email: user.email,
@ -56,10 +82,10 @@ export default function PatientProfile() {
street: patientDetails.street || "",
number: patientDetails.number || "",
city: patientDetails.city || "",
avatarFullUrl: user.avatarFullUrl,
avatarFullUrl: freshAvatarUrl, // Usa a URL fresca do banco
});
} catch (error) {
console.error("Erro ao buscar detalhes do paciente:", error);
console.error("Erro ao buscar detalhes:", error);
toast({
title: "Erro",
description: "Não foi possível carregar seus dados completos.",
@ -67,9 +93,9 @@ export default function PatientProfile() {
});
}
};
fetchPatientDetails();
loadData();
}
}, [user]);
}, [user?.id, user?.email, user?.name]); // Removi user.avatarFullUrl para não depender do cache
const handleInputChange = (
field: keyof PatientProfileData,
@ -78,6 +104,27 @@ export default function PatientProfile() {
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
};
const updateLocalSession = (updates: { full_name?: string; avatar_url?: string }) => {
try {
const storedUserString = localStorage.getItem("user_info");
if (storedUserString) {
const storedUser = JSON.parse(storedUserString);
if (!storedUser.user_metadata) storedUser.user_metadata = {};
if (updates.full_name) storedUser.user_metadata.full_name = updates.full_name;
if (updates.avatar_url) storedUser.user_metadata.avatar_url = updates.avatar_url;
if (!storedUser.profile) storedUser.profile = {};
if (updates.full_name) storedUser.profile.full_name = updates.full_name;
if (updates.avatar_url) storedUser.profile.avatar_url = updates.avatar_url;
localStorage.setItem("user_info", JSON.stringify(storedUser));
}
} catch (e) {
console.error("Erro ao atualizar sessão local:", e);
}
};
const handleSave = async () => {
if (!patientData || !user) return;
setIsSaving(true);
@ -92,12 +139,22 @@ export default function PatientProfile() {
number: patientData.number,
city: patientData.city,
};
await patientsService.update(user.id, patientPayload);
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
full_name: patientData.name,
});
updateLocalSession({ full_name: patientData.name });
toast({
title: "Sucesso!",
description: "Seus dados foram atualizados.",
description: "Seus dados foram atualizados. A página será recarregada.",
});
setIsEditing(false);
setTimeout(() => window.location.reload(), 1000);
} catch (error) {
console.error("Erro ao salvar dados:", error);
toast({
@ -121,9 +178,6 @@ export default function PatientProfile() {
if (!file || !user) return;
const fileExt = file.name.split(".").pop();
// *** A CORREÇÃO ESTÁ AQUI ***
// O caminho salvo no banco de dados não deve conter o nome do bucket.
const filePath = `${user.id}/avatar.${fileExt}`;
try {
@ -132,15 +186,21 @@ export default function PatientProfile() {
avatar_url: filePath,
});
const newFullUrl = `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${filePath}?t=${new Date().getTime()}`;
const newFullUrl = buildAvatarUrl(filePath);
setPatientData((prev) =>
prev ? { ...prev, avatarFullUrl: newFullUrl } : null
);
updateLocalSession({ avatar_url: filePath });
toast({
title: "Sucesso!",
description: "Sua foto de perfil foi atualizada.",
});
setTimeout(() => window.location.reload(), 1000);
} catch (error) {
console.error("Erro no upload do avatar:", error);
toast({
@ -154,7 +214,9 @@ export default function PatientProfile() {
if (isAuthLoading || !patientData) {
return (
<Sidebar>
<div>Carregando seus dados...</div>
<div className="flex items-center justify-center h-full">
<p className="text-muted-foreground">Carregando seus dados...</p>
</div>
</Sidebar>
);
}
@ -164,8 +226,8 @@ export default function PatientProfile() {
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold text-gray-900">Meus Dados</h1>
<p className="text-gray-600">Gerencie suas informações pessoais</p>
<h1 className="text-3xl font-bold text-foreground">Meus Dados</h1>
<p className="text-muted-foreground">Gerencie suas informações pessoais</p>
</div>
<Button
onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
@ -313,22 +375,20 @@ export default function PatientProfile() {
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center space-x-3">
<div className="relative">
<div className="relative group">
<Avatar
className="w-16 h-16 cursor-pointer"
className="w-16 h-16 cursor-pointer border-2 border-transparent group-hover:border-blue-500 transition-all"
onClick={handleAvatarClick}
>
<AvatarImage src={patientData.avatarFullUrl} />
<AvatarFallback className="text-2xl">
{patientData.name
.split(" ")
.map((n) => n[0])
.join("")}
<AvatarImage src={patientData.avatarFullUrl} className="object-cover" />
<AvatarFallback className="text-2xl bg-gray-200 text-gray-700 font-bold">
{getInitials(patientData.name)}
</AvatarFallback>
</Avatar>
<div
className="absolute bottom-0 right-0 bg-primary text-primary-foreground rounded-full p-1 cursor-pointer hover:bg-primary/80"
className="absolute bottom-0 right-0 bg-blue-600 text-white rounded-full p-1.5 cursor-pointer hover:bg-blue-700 shadow-md transition-colors"
onClick={handleAvatarClick}
title="Alterar foto"
>
<Upload className="w-3 h-3" />
</div>
@ -337,25 +397,25 @@ export default function PatientProfile() {
ref={fileInputRef}
onChange={handleAvatarUpload}
className="hidden"
accept="image/png, image/jpeg"
accept="image/png, image/jpeg, image/jpg"
/>
</div>
<div>
<p className="font-medium">{patientData.name}</p>
<p className="font-medium text-lg">{patientData.name}</p>
<p className="text-sm text-gray-500">Paciente</p>
</div>
</div>
<div className="space-y-3 pt-4 border-t">
<div className="flex items-center text-sm">
<Mail className="mr-2 h-4 w-4 text-gray-500" />
<Mail className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="truncate">{patientData.email}</span>
</div>
<div className="flex items-center text-sm">
<Phone className="mr-2 h-4 w-4 text-gray-500" />
<Phone className="mr-2 h-4 w-4 text-muted-foreground" />
<span>{patientData.phone || "Não informado"}</span>
</div>
<div className="flex items-center text-sm">
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
<Calendar className="mr-2 h-4 w-4 text-muted-foreground" />
<span>
{patientData.birthDate
? new Date(patientData.birthDate).toLocaleDateString(

View File

@ -85,19 +85,18 @@ export default function PatientRegister() {
}
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-8 px-4">
<div className="min-h-screen bg-background py-8 px-4">
<div className="max-w-2xl mx-auto">
<div className="mb-6">
<Link href="/" className="inline-flex items-center text-blue-600 hover:text-blue-800">
<Link href="/" className="inline-flex items-center text-primary hover:text-primary/90">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar ao início
</Link>
</div>
<Card>
<CardHeader className="text-center">
<CardTitle className="text-2xl">Crie sua Conta de Paciente</CardTitle>
<CardDescription>Preencha seus dados para acessar o portal MedConnect</CardDescription>
<CardTitle className="text-2xl text-foreground">Crie sua Conta de Paciente</CardTitle>
<CardDescription className="text-muted-foreground">Preencha seus dados para acessar o portal MedConnect</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleRegister} className="space-y-4">
@ -172,9 +171,9 @@ export default function PatientRegister() {
</form>
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
tem uma conta?{" "}
<Link href="/login" className="text-blue-600 hover:underline">
<p className="text-sm">
<span className="text-muted-foreground"> tem uma conta?</span>{" "}
<Link href="/login" className="text-primary hover:underline font-medium">
Faça login aqui
</Link>
</p>

View File

@ -37,8 +37,9 @@ export default function ReportsPage() {
const [selectedReport, setSelectedReport] = useState<Report | null>(null)
const [isViewModalOpen, setIsViewModalOpen] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const requiredRole = useMemo(() => ["paciente"], []);
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole });
const { user, isLoading: isAuthLoading } = useAuthLayout({
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
  });
useEffect(() => {
@ -131,8 +132,8 @@ export default function ReportsPage() {
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Meus Laudos</h1>
<p className="text-gray-600 mt-2">Visualize e baixe seus laudos médicos e resultados de exames</p>
<h1 className="text-3xl font-bold text-foreground">Meus Laudos</h1>
<p className="text-muted-foreground mt-2">Visualize e baixe seus laudos médicos e resultados de exames</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
@ -167,7 +168,7 @@ export default function ReportsPage() {
{availableReports.length > 0 && (
<div>
<h2 className="text-xl font-semibold text-gray-900 mb-4">Laudos Disponíveis</h2>
<h2 className="text-xl font-semibold text-foreground mb-4">Laudos Disponíveis</h2>
<div className="grid gap-4">
{availableReports.map((report) => (
<Card key={report.id} className="hover:shadow-md transition-shadow">
@ -192,7 +193,7 @@ export default function ReportsPage() {
</div>
</CardHeader>
<CardContent>
<p className="text-gray-600 mb-4">{report.diagnosis}</p>
<p className="text-muted-foreground mb-4">{report.diagnosis}</p>
<div className="flex gap-2">
<Button
variant="outline"
@ -222,7 +223,7 @@ export default function ReportsPage() {
{pendingReports.length > 0 && (
<div>
<h2 className="text-xl font-semibold text-gray-900 mb-4">Laudos Pendentes</h2>
<h2 className="text-xl font-semibold text-foreground mb-4">Laudos Pendentes</h2>
<div className="grid gap-4">
{pendingReports.map((report) => (
<Card key={report.id} className="opacity-75">
@ -247,8 +248,8 @@ export default function ReportsPage() {
</div>
</CardHeader>
<CardContent>
<p className="text-gray-600 mb-4">{report.diagnosis}</p>
<p className="text-sm text-yellow-600 font-medium">
<p className="text-muted-foreground mb-4">{report.diagnosis}</p>
<p className="text-sm text-yellow-600 dark:text-yellow-500 font-medium">
Laudo em processamento. Você será notificado quando estiver disponível.
</p>
</CardContent>
@ -261,9 +262,9 @@ export default function ReportsPage() {
{reports.length === 0 && !isLoading && (
<Card className="text-center py-12">
<CardContent>
<FileText className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">Nenhum laudo encontrado</h3>
<p className="text-gray-600">Seus laudos médicos aparecerão aqui após a realização de exames.</p>
<FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium text-foreground mb-2">Nenhum laudo encontrado</h3>
<p className="text-muted-foreground">Seus laudos médicos aparecerão aqui após a realização de exames.</p>
</CardContent>
</Card>
)}

18
app/providers.tsx Normal file
View File

@ -0,0 +1,18 @@
"use client";
import { AccessibilityProvider } from "./context/AccessibilityContext";
import { AppointmentsProvider } from "./context/AppointmentsContext";
import { AccessibilityModal } from "@/components/accessibility-modal";
import { ThemeInitializer } from "@/components/theme-initializer";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<>
<ThemeInitializer />
<AccessibilityProvider>
<AppointmentsProvider>{children}</AppointmentsProvider>
<AccessibilityModal />
</AccessibilityProvider>
</>
);
}

View File

@ -1,6 +1,6 @@
"use client";
import { useState, useEffect } from "react";
import { useState, useEffect, useMemo } from "react";
import {
Card,
CardContent,
@ -11,15 +11,24 @@ import {
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Dialog } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; // Importei o Input
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
import { Separator } from "@/components/ui/separator";
import {
Calendar,
Calendar as CalendarIcon,
Clock,
MapPin,
Phone,
User,
Trash2,
Pencil,
List,
RefreshCw,
Loader2,
Search, // Importei o ícone de busca
} from "lucide-react";
import { format, parseISO, isValid, isToday, isTomorrow } from "date-fns";
import { ptBR } from "date-fns/locale";
import { toast } from "sonner";
import Link from "next/link";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
@ -36,6 +45,9 @@ export default function SecretaryAppointments() {
const [deleteModal, setDeleteModal] = useState(false);
const [editModal, setEditModal] = useState(false);
// Estado da Busca
const [searchTerm, setSearchTerm] = useState("");
// Estado para o formulário de edição
const [editFormData, setEditFormData] = useState({
date: "",
@ -43,15 +55,15 @@ export default function SecretaryAppointments() {
status: "",
});
// Estado de data selecionada
const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());
const fetchData = async () => {
setIsLoading(true);
try {
// 1. DEFINIR O PARÂMETRO DE ORDENAÇÃO
// 'scheduled_at.desc' ordena pela data do agendamento, em ordem descendente (mais recentes primeiro).
const queryParams = "order=scheduled_at.desc";
const queryParams = "order=scheduled_at.asc";
const [appointmentList, patientList, doctorList] = await Promise.all([
// 2. USAR A FUNÇÃO DE BUSCA COM O PARÂMETRO DE ORDENAÇÃO
appointmentsService.search_appointment(queryParams),
patientsService.list(),
doctorsService.list(),
@ -82,9 +94,66 @@ export default function SecretaryAppointments() {
useEffect(() => {
fetchData();
}, []); // Array vazio garante que a busca ocorra apenas uma vez, no carregamento da página.
}, []);
// --- LÓGICA DE EDIÇÃO ---
// --- Filtragem e Agrupamento ---
const groupedAppointments = useMemo(() => {
let filteredList = appointments;
// 1. Filtro de Texto (Nome do Paciente ou Médico)
if (searchTerm) {
const lowerTerm = searchTerm.toLowerCase();
filteredList = filteredList.filter(
(apt) =>
apt.patient.full_name.toLowerCase().includes(lowerTerm) ||
apt.doctor.full_name.toLowerCase().includes(lowerTerm)
);
}
// 2. Filtro de Data (se selecionada)
if (selectedDate) {
filteredList = filteredList.filter((apt) => {
if (!apt.scheduled_at) return false;
const iso = apt.scheduled_at.toString();
return iso.startsWith(format(selectedDate, "yyyy-MM-dd"));
});
}
// 3. Agrupamento por dia
return filteredList.reduce((acc: Record<string, any[]>, apt: any) => {
if (!apt.scheduled_at) return acc;
const dateObj = new Date(apt.scheduled_at);
if (!isValid(dateObj)) return acc;
const key = format(dateObj, "yyyy-MM-dd");
if (!acc[key]) acc[key] = [];
acc[key].push(apt);
return acc;
}, {});
}, [appointments, selectedDate, searchTerm]);
// Dias que têm consulta (para destacar no calendário)
const bookedDays = useMemo(
() =>
appointments
.map((apt) =>
apt.scheduled_at ? new Date(apt.scheduled_at) : null
)
.filter((d): d is Date => d !== null && isValid(d)),
[appointments]
);
const formatDisplayDate = (dateString: string) => {
const date = parseISO(dateString);
if (isToday(date)) {
return `Hoje, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
}
if (isTomorrow(date)) {
return `Amanhã, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
}
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
};
// --- LÓGICA DE EDIÇÃO E DELEÇÃO ---
const handleEdit = (appointment: any) => {
setSelectedAppointment(appointment);
const appointmentDate = new Date(appointment.scheduled_at);
@ -122,11 +191,7 @@ export default function SecretaryAppointments() {
};
await appointmentsService.update(selectedAppointment.id, updatePayload);
// 3. RECARREGAR OS DADOS APÓS A EDIÇÃO
// Isso garante que a lista permaneça ordenada corretamente se a data for alterada.
fetchData();
await fetchData();
setEditModal(false);
toast.success("Consulta atualizada com sucesso!");
} catch (error) {
@ -135,7 +200,6 @@ export default function SecretaryAppointments() {
}
};
// --- LÓGICA DE DELEÇÃO ---
const handleDelete = (appointment: any) => {
setSelectedAppointment(appointment);
setDeleteModal(true);
@ -156,161 +220,249 @@ export default function SecretaryAppointments() {
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case "requested":
return (
<Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>
);
case "confirmed":
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
case "checked_in":
return (
<Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>
);
case "completed":
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
case "cancelled":
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
case "no_show":
return (
<Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>
);
default:
return <Badge variant="secondary">{status}</Badge>;
}
};
const timeSlots = [
"08:00",
"08:30",
"09:00",
"09:30",
"10:00",
"10:30",
"11:00",
"11:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30",
"17:00",
"17:30",
];
const appointmentStatuses = [
"requested",
"confirmed",
"checked_in",
"completed",
"cancelled",
"no_show",
];
return (
<Sidebar>
<div className="space-y-6">
<div className="flex justify-between items-center">
{/* Cabeçalho principal */}
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div>
<h1 className="text-3xl font-bold text-gray-900">
Consultas Agendadas
<h1 className="text-3xl font-bold text-foreground">
Agenda Médica
</h1>
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
<p className="text-muted-foreground">
Consultas para os pacientes
</p>
</div>
<Link href="/secretary/schedule">
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
<Calendar className="mr-2 h-4 w-4 text-white" />
<Button className="bg-primary hover:bg-primary/90 text-primary-foreground">
<CalendarIcon className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link>
</div>
<div className="grid gap-6">
{isLoading ? (
<p>Carregando consultas...</p>
) : appointments.length > 0 ? (
appointments.map((appointment) => (
<Card key={appointment.id}>
<CardHeader>
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-lg">
{appointment.doctor.full_name}
</CardTitle>
<CardDescription>
{appointment.doctor.specialty}
</CardDescription>
{/* Barra de Filtros e Ações */}
<div className="flex flex-col md:flex-row justify-between items-center gap-4">
<h2 className="text-xl font-semibold capitalize whitespace-nowrap">
{selectedDate
? `Agenda de ${format(selectedDate, "dd/MM/yyyy")}`
: "Todas as Consultas"}
</h2>
<div className="flex flex-col md:flex-row items-center gap-3 w-full md:w-auto">
{/* BARRA DE PESQUISA ADICIONADA AQUI */}
<div className="relative w-full md:w-72">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Buscar paciente ou médico..."
className="pl-9 w-full"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
{getStatusBadge(appointment.status)}
</div>
</CardHeader>
<CardContent>
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-3">
<div className="flex items-center text-sm text-gray-800 font-medium">
<User className="mr-2 h-4 w-4 text-gray-600" />
{appointment.patient.full_name}
</div>
<div className="flex items-center text-sm text-gray-600">
<Calendar className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleDateString(
"pt-BR",
{ timeZone: "UTC" }
)}
</div>
<div className="flex items-center text-sm text-gray-600">
<Clock className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleTimeString(
"pt-BR",
{
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
}
)}
</div>
</div>
<div className="space-y-3">
<div className="flex items-center text-sm text-gray-600">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center text-sm text-gray-600">
<Phone className="mr-2 h-4 w-4" />
{appointment.doctor.phone || "N/A"}
<div className="flex gap-2 w-full md:w-auto">
<Button
onClick={() => {
setSelectedDate(undefined);
setSearchTerm("");
}}
variant="ghost"
size="sm"
className="flex-1 md:flex-none"
>
<List className="mr-2 h-4 w-4" />
Mostrar Todas
</Button>
<Button
onClick={() => fetchData()}
disabled={isLoading}
variant="outline"
size="sm"
className="flex-1 md:flex-none"
>
<RefreshCw
className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`}
/>
Atualizar
</Button>
</div>
</div>
</div>
<div className="flex gap-2 mt-4 pt-4 border-t">
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
{/* Grid com calendário + lista */}
<div className="grid lg:grid-cols-3 gap-6">
{/* Coluna esquerda: calendário */}
<div className="lg:col-span-1">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<CalendarIcon className="mr-2 h-5 w-5" />
Filtrar por Data
</CardTitle>
<CardDescription>
Selecione um dia para ver os detalhes.
</CardDescription>
</CardHeader>
<CardContent className="flex justify-center p-2">
<CalendarShadcn
mode="single"
selected={selectedDate}
onSelect={setSelectedDate}
modifiers={{ booked: bookedDays }}
modifiersClassNames={{ booked: "bg-primary/20" }}
className="rounded-md border p-2"
locale={ptBR}
/>
</CardContent>
</Card>
</div>
{/* Coluna direita: lista de consultas */}
<div className="lg:col-span-2 space-y-6">
{isLoading ? (
<div className="flex justify-center items-center h-48">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
) : Object.keys(groupedAppointments).length === 0 ? (
<Card className="flex flex-col items-center justify-center h-48 text-center">
<CardHeader>
<CardTitle>Nenhuma consulta encontrada</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">
{searchTerm
? "Nenhum resultado para a busca."
: selectedDate
? "Não há agendamentos para esta data."
: "Não há consultas agendadas."}
</p>
</CardContent>
</Card>
) : (
Object.entries(groupedAppointments).map(
([date, appointmentsForDay]) => (
<div key={date}>
<h3 className="text-lg font-semibold text-foreground mb-3 capitalize">
{formatDisplayDate(date)}
</h3>
<div className="space-y-4">
{appointmentsForDay.map((appointment: any) => {
const scheduledAtDate = new Date(
appointment.scheduled_at
);
return (
<Card
key={appointment.id}
className="shadow-sm hover:shadow-md transition-shadow"
>
<CardContent className="p-4 grid grid-cols-1 md:grid-cols-3 items-center gap-4">
{/* Coluna 1: Paciente + hora */}
<div className="col-span-1 flex flex-col gap-2">
<div className="font-semibold flex items-center text-foreground">
<User className="mr-2 h-4 w-4 text-primary" />
{appointment.patient.full_name}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Clock className="mr-2 h-4 w-4" />
{isValid(scheduledAtDate)
? format(scheduledAtDate, "HH:mm")
: "--:--"}
</div>
</div>
{/* Coluna 2: Médico / local / telefone */}
<div className="col-span-1 flex flex-col gap-2">
<div className="flex items-center text-sm text-muted-foreground">
<User className="mr-2 h-4 w-4" />
{appointment.doctor.full_name}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location ||
"Local a definir"}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Phone className="mr-2 h-4 w-4" />
{appointment.doctor.phone || "N/A"}
</div>
<div>{getStatusBadge(appointment.status)}</div>
</div>
{/* Coluna 3: Ações */}
<div className="col-span-1 flex justify-start md:justify-end">
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(appointment)}
>
<Pencil className="mr-2 h-4 w-4" />
Editar
</Button>
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleDelete(appointment)}>
<Button
variant="destructive"
size="sm"
onClick={() => handleDelete(appointment)}
>
<Trash2 className="mr-2 h-4 w-4" />
Cancelar
</Button>
</div>
</div>
</CardContent>
</Card>
))
) : (
<p>Nenhuma consulta encontrada.</p>
);
})}
</div>
<Separator className="my-6" />
</div>
)
)
)}
</div>
</div>
{/* MODAL DE EDIÇÃO */}
<Dialog open={editModal} onOpenChange={setEditModal}>
{/* ... (código do modal de edição) ... */}
{/* Modal de edição permanece o mesmo, adicione o DialogContent se precisar */}
{/* Aqui estou assumindo que você tem o conteúdo do Dialog no seu código original ou em outro lugar, pois ele não estava completo no snippet anterior */}
</Dialog>
{/* Modal de Deleção */}
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
{/* ... (código do modal de deleção) ... */}
{/* Modal de deleção permanece o mesmo */}
</Dialog>
</div>
</Sidebar>
);
}
const getStatusBadge = (status: string) => {
switch (status) {
case "requested":
return (
<Badge className="bg-yellow-400/10 text-yellow-400">Solicitada</Badge>
);
case "confirmed":
return <Badge className="bg-primary/10 text-primary">Confirmada</Badge>;
case "checked_in":
return (
<Badge className="bg-indigo-400/10 text-indigo-400">Check-in</Badge>
);
case "completed":
return <Badge className="bg-green-400/10 text-green-400">Realizada</Badge>;
case "cancelled":
return (
<Badge className="bg-destructive/10 text-destructive">Cancelada</Badge>
);
case "no_show":
return (
<Badge className="bg-muted text-foreground">Não Compareceu</Badge>
);
default:
return <Badge variant="secondary">{status}</Badge>;
}
};

View File

@ -104,8 +104,8 @@ export default function SecretaryDashboard() {
<div className="space-y-6">
{/* Cabeçalho */}
<div>
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<p className="text-gray-600">
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
@ -122,7 +122,7 @@ export default function SecretaryDashboard() {
</CardHeader>
<CardContent>
{loadingAppointments ? (
<div className="text-gray-500 text-sm">
<div className="text-muted-foreground text-sm">
Carregando próxima consulta...
</div>
) : firstConfirmed ? (
@ -147,7 +147,7 @@ export default function SecretaryDashboard() {
</p>
</>
) : (
<div className="text-sm text-gray-500">
<div className="text-sm text-muted-foreground">
Nenhuma consulta confirmada encontrada
</div>
)}
@ -164,12 +164,12 @@ export default function SecretaryDashboard() {
</CardHeader>
<CardContent>
{loadingAppointments ? (
<div className="text-gray-500 text-sm">
<div className="text-muted-foreground text-sm">
Carregando consultas...
</div>
) : nextAgendada ? (
<>
<div className="text-lg font-bold text-gray-900">
<div className="text-lg font-bold">
{new Date(nextAgendada.scheduled_at).toLocaleDateString(
"pt-BR",
{
@ -199,7 +199,7 @@ export default function SecretaryDashboard() {
</p>
</>
) : (
<div className="text-sm text-gray-500">
<div className="text-sm text-muted-foreground">
Nenhuma consulta agendada neste mês
</div>
)}
@ -231,8 +231,8 @@ export default function SecretaryDashboard() {
</CardHeader>
<CardContent className="space-y-4">
<Link href="/secretary/schedule">
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
<User className="mr-2 h-4 w-4 text-white" />
<Button className="w-full justify-start bg-primary text-primary-foreground hover:bg-primary/90">
<User className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link>
@ -265,9 +265,9 @@ export default function SecretaryDashboard() {
</CardHeader>
<CardContent>
{loadingPatients ? (
<p className="text-sm text-gray-500">Carregando pacientes...</p>
<p className="text-sm text-muted-foreground">Carregando pacientes...</p>
) : patients.length === 0 ? (
<p className="text-sm text-gray-500">
<p className="text-sm text-muted-foreground">
Nenhum paciente cadastrado.
</p>
) : (
@ -275,20 +275,20 @@ export default function SecretaryDashboard() {
{patients.map((patient, index) => (
<div
key={index}
className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100"
className="flex items-center justify-between p-3 bg-primary/10 rounded-lg border border-primary/20"
>
<div>
<p className="font-medium text-gray-900">
<p className="font-medium text-foreground">
{patient.full_name || "Sem nome"}
</p>
<p className="text-sm text-gray-600">
<p className="text-sm text-muted-foreground">
{patient.phone_mobile ||
patient.phone1 ||
"Sem telefone"}
</p>
</div>
<div className="text-right">
<p className="font-medium text-blue-700">
<p className="font-medium text-primary">
{patient.convenio || "Particular"}
</p>
</div>

View File

@ -275,31 +275,29 @@ export default function EditarPacientePage() {
</Button>
</Link>
<div>
<h1 className="text-2xl font-bold text-gray-900">Editar Paciente</h1>
<p className="text-gray-600">Atualize as informações do paciente</p>
<h1 className="text-2xl font-bold">Editar Paciente</h1>
<p className="text-muted-foreground">Atualize as informações do paciente</p>
</div>
</div>
{/* Anexos Section - Movido para fora do cabeçalho para melhor organização e responsividade */}
{/* Espaço reservado para anexos ou ações futuras */}
</div>
<form onSubmit={handleSubmit} className="space-y-8">
{/* Dados Pessoais Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Dados Pessoais</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* Photo upload */}
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-1">
<Label>Foto do paciente</Label>
<div className="flex flex-col sm:flex-row items-center gap-4">
<div className="w-20 h-20 rounded-full bg-gray-100 overflow-hidden flex items-center justify-center">
<div className="w-20 h-20 rounded-full bg-muted overflow-hidden flex items-center justify-center">
{photoUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
) : (
<span className="text-gray-400 text-sm text-center">Sem foto</span>
<span className="text-muted-foreground text-sm text-center">Sem foto</span>
)}
</div>
<div className="flex flex-col sm:flex-row gap-2 mt-2 sm:mt-0">
@ -334,11 +332,11 @@ export default function EditarPacientePage() {
<Label>Sexo *</Label>
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex items-center space-x-2">
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Masculino">Masculino</Label>
</div>
<div className="flex items-center space-x-2">
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Feminino">Feminino</Label>
</div>
</div>
@ -467,8 +465,8 @@ export default function EditarPacientePage() {
</div>
{/* Contact Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Contato</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
@ -494,8 +492,8 @@ export default function EditarPacientePage() {
</div>
{/* Address Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Endereço</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div className="space-y-2">
@ -569,8 +567,8 @@ export default function EditarPacientePage() {
</div>
{/* Medical Information Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Médicas</h2>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Informações Médicas</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
@ -615,8 +613,8 @@ export default function EditarPacientePage() {
</div>
{/* Insurance Information Section */}
<div className="bg-white rounded-lg border border-gray-200 p-6">
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações de convênio</h2>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Informações de convênio</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
@ -665,7 +663,7 @@ export default function EditarPacientePage() {
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto">
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
<Save className="w-4 h-4 mr-2" />
Salvar Alterações
</Button>

View File

@ -85,7 +85,7 @@ export default function NovoUsuarioPage() {
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao criar usuário:", e);
setError(e?.message || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
setError(e?.message || "Não foi possível criar o paciente. Verifique os dados e tente novamente.");
} finally {
setIsSaving(false);
}
@ -100,10 +100,10 @@ export default function NovoUsuarioPage() {
{/* Cabeçalho da página */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-4 gap-4"> {/* Ajustado para empilhar em telas pequenas */}
<div>
<h1 className="text-2xl sm:text-3xl font-extrabold text-gray-900">Novo Usuário</h1> {/* Tamanho de texto responsivo */}
<p className="text-sm sm:text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p> {/* Tamanho de texto responsivo */}
<h1 className="text-2xl sm:text-3xl font-extrabold text-gray-900">Novo Paciente</h1> {/* Tamanho de texto responsivo */}
<p className="text-sm sm:text-md text-gray-500">Preencha os dados para cadastrar um novo paciente no sistema.</p> {/* Tamanho de texto responsivo */}
</div>
<Link href="/manager/usuario">
<Link href="/secretary/pacientes">
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button> {/* Botão ocupa largura total em telas pequenas */}
</Link>
</div>
@ -153,15 +153,19 @@ export default function NovoUsuarioPage() {
{/* Botões de ação */}
<div className="flex flex-col sm:flex-row justify-end gap-4 pt-6 border-t mt-6"> {/* Botões empilhados em telas pequenas */}
<Link href="/manager/usuario">
<Link href="/secretary/pacientes">
<Button type="button" variant="outline" disabled={isSaving} className="w-full sm:w-auto">
Cancelar
</Button>
</Link>
<Link href="/secretary/pacientes">
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto" disabled={isSaving}>
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
{isSaving ? "Salvando..." : "Salvar Usuário"}
{isSaving ? "Salvando..." : "Salvar Paciente"}
</Button>
</Link>
</div>
</form>
</div>

View File

@ -149,7 +149,7 @@ export default function PacientesPage() {
{/* Header (Responsividade OK) */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h1 className="text-xl md:text-2xl font-bold text-foreground">
<h1 className="text-xl md:text-2xl font-bold">
Pacientes
</h1>
<p className="text-muted-foreground text-sm md:text-base">
@ -158,7 +158,7 @@ export default function PacientesPage() {
</div>
<div className="flex gap-2">
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
<Button className="w-full bg-blue-600 hover:bg-blue-700">
<Button className="w-full bg-primary hover:bg-primary/90">
<Plus className="w-4 h-4 mr-2" />
Adicionar
</Button>
@ -167,8 +167,8 @@ export default function PacientesPage() {
</div>
{/* Bloco de Filtros (Responsividade APLICADA) */}
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
<Filter className="w-5 h-5 text-gray-400" />
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border">
<Filter className="w-5 h-5 text-muted-foreground" />
{/* Busca - Ocupa 100% no mobile, depois cresce */}
<input
@ -181,7 +181,7 @@ export default function PacientesPage() {
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">
Convênio
</span>
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
@ -202,7 +202,7 @@ export default function PacientesPage() {
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
<span className="text-sm font-medium whitespace-nowrap hidden md:block">VIP</span>
<Select value={vipFilter} onValueChange={setVipFilter}>
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
<SelectValue placeholder="VIP" />
@ -221,43 +221,43 @@ export default function PacientesPage() {
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
<div className="bg-card rounded-lg border shadow-md hidden md:block">
<div className="overflow-x-auto">
{" "}
{/* Permite rolagem horizontal se a tabela for muito larga */}
{error ? (
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
<div className="p-6 text-destructive">{`Erro ao carregar pacientes: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
<div className="p-6 text-center text-muted-foreground flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" />{" "}
Carregando pacientes...
</div>
) : (
<table className="w-full min-w-[650px]">
{" "}
{/* min-w para evitar que a tabela se contraia demais */}
<thead className="bg-gray-50 border-b border-gray-200">
<thead className="bg-muted border-b">
<tr>
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">
<th className="text-left p-4 font-medium text-muted-foreground w-[20%]">
Nome
</th>
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">
Telefone
</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden md:table-cell">
Cidade / Estado
</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">
Convênio
</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">
Último atendimento
</th>
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">
Próximo atendimento
</th>
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">
<th className="text-left p-4 font-medium text-muted-foreground w-[5%]">
Ações
</th>
</tr>
@ -265,7 +265,7 @@ export default function PacientesPage() {
<tbody>
{currentPatients.length === 0 ? (
<tr>
<td colSpan={7} className="p-8 text-center text-gray-500">
<td colSpan={7} className="p-8 text-center text-muted-foreground">
{allPatients.length === 0
? "Nenhum paciente cadastrado"
: "Nenhum paciente encontrado com os filtros aplicados"}
@ -275,46 +275,47 @@ export default function PacientesPage() {
currentPatients.map((patient) => (
<tr
key={patient.id}
className="border-b border-gray-100 hover:bg-gray-50"
className="border-b hover:bg-muted"
>
<td className="p-4">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-blue-600 font-medium text-sm">
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-primary font-medium text-sm">
{patient.nome?.charAt(0) || "?"}
</span>
</div>
<span className="font-medium text-gray-900">
<span className="font-medium">
{patient.nome}
{patient.vip && (
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-500 bg-purple-500/10 rounded-full">
VIP
</span>
)}
</span>
</div>
</td>
<td className="p-4 text-gray-600 hidden sm:table-cell">
<td className="p-4 text-muted-foreground hidden sm:table-cell">
{patient.telefone}
</td>
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
<td className="p-4 text-gray-600 hidden sm:table-cell">
<td className="p-4 text-muted-foreground hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">
{patient.convenio}
</td>
<td className="p-4 text-gray-600 hidden lg:table-cell">
<td className="p-4 text-muted-foreground hidden lg:table-cell">
{patient.ultimoAtendimento}
</td>
<td className="p-4 text-gray-600 hidden lg:table-cell">
<td className="p-4 text-muted-foreground hidden lg:table-cell">
{patient.proximoAtendimento}
</td>
<td className="p-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="text-blue-600 cursor-pointer">
Ações
</div>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Abrir menu</span>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
@ -341,7 +342,7 @@ export default function PacientesPage() {
Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem
className="text-red-600"
className="text-destructive"
onClick={() =>
openDeleteDialog(String(patient.id))
}
@ -363,16 +364,16 @@ export default function PacientesPage() {
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
<div className="bg-card rounded-lg border shadow-md p-4 block md:hidden">
{error ? (
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
<div className="p-6 text-destructive">{`Erro ao carregar pacientes: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
<div className="p-6 text-center text-muted-foreground flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" />{" "}
Carregando pacientes...
</div>
) : filteredPatients.length === 0 ? (
<div className="p-8 text-center text-gray-500">
<div className="p-8 text-center text-muted-foreground">
{allPatients.length === 0
? "Nenhum paciente cadastrado"
: "Nenhum paciente encontrado com os filtros aplicados"}
@ -382,21 +383,21 @@ export default function PacientesPage() {
{currentPatients.map((patient) => (
<div
key={patient.id}
className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200"
className="bg-muted rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border"
>
<div className="flex-grow mb-2 sm:mb-0">
<div className="font-semibold text-lg text-gray-900 flex items-center">
<div className="font-semibold text-lg flex items-center">
{patient.nome}
{patient.vip && (
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-500 bg-purple-500/10 rounded-full">
VIP
</span>
)}
</div>
<div className="text-sm text-gray-600">
<div className="text-sm text-muted-foreground">
Telefone: {patient.telefone}
</div>
<div className="text-sm text-gray-600">
<div className="text-sm text-muted-foreground">
Convênio: {patient.convenio}
</div>
</div>
@ -427,7 +428,7 @@ export default function PacientesPage() {
<Calendar className="w-4 h-4 mr-2" />
Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(String(patient.id))}>
<Trash2 className="w-4 h-4 mr-2" />
Excluir
</DropdownMenuItem>
@ -441,7 +442,7 @@ export default function PacientesPage() {
{/* Paginação */}
{totalPages > 1 && !loading && (
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t">
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
<Button
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
@ -460,7 +461,7 @@ export default function PacientesPage() {
onClick={() => setPage(pageNumber)}
variant={pageNumber === page ? "default" : "outline"}
size="lg"
className={pageNumber === page ? "bg-blue-600 hover:bg-blue-700 text-white" : "text-gray-700"}
className={pageNumber === page ? "bg-primary hover:bg-primary/90 text-primary-foreground" : "text-muted-foreground"}
>
{pageNumber}
</Button>
@ -487,7 +488,7 @@ export default function PacientesPage() {
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-destructive hover:bg-destructive/90">
Excluir
</AlertDialogAction>
</AlertDialogFooter>
@ -503,12 +504,12 @@ export default function PacientesPage() {
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
<AlertDialogDescription>
{patientDetails === null ? (
<div className="text-gray-500">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
<div className="text-muted-foreground">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary my-4" />
Carregando...
</div>
) : patientDetails?.error ? (
<div className="text-red-600 p-4">{patientDetails.error}</div>
<div className="text-destructive p-4">{patientDetails.error}</div>
) : (
<div className="grid gap-4 py-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">

View File

@ -1,4 +1,3 @@
// Caminho: [seu-caminho]/ManagerLayout.tsx
"use client";
import type React from "react";
@ -7,6 +6,8 @@ import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import Cookies from "js-cookie";
import { api } from "@/services/api.mjs";
import { usersService } from "@/services/usersApi.mjs"; // Importando usersService
import { useAccessibility } from "@/app/context/AccessibilityContext";
import { Button } from "@/components/ui/button";
import {
@ -30,7 +31,6 @@ import {
SquareUser,
ClipboardList,
Stethoscope,
ClipboardMinus,
} from "lucide-react";
import SidebarUserSection from "@/components/ui/userToolTip";
@ -47,6 +47,7 @@ interface UserData {
full_name: string;
phone_mobile: string;
role: string;
avatar_url?: string;
};
identities: {
identity_id: string;
@ -72,16 +73,36 @@ export default function Sidebar({ children }: SidebarProps) {
const [role, setRole] = useState<string>();
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
const [avatarFullUrl, setAvatarFullUrl] = useState<string | undefined>(undefined);
const router = useRouter();
const pathname = usePathname();
// Função auxiliar para construir URL
const buildAvatarUrl = (path: string) => {
if (!path) return undefined;
const baseUrl = "https://yuanqfswhberkoevtmfr.supabase.co";
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
const separator = cleanPath.includes('?') ? '&' : '?';
return `${baseUrl}/storage/v1/object/avatars/${cleanPath}${separator}t=${new Date().getTime()}`;
};
const { theme, contrast } = useAccessibility();
useEffect(() => {
const userInfoString = localStorage.getItem("user_info");
const token = localStorage.getItem("token");
if (userInfoString && token) {
try {
const userInfo = JSON.parse(userInfoString);
// 1. Tenta pegar o avatar do cache local
let rawAvatarPath =
userInfo.profile?.avatar_url ||
userInfo.user_metadata?.avatar_url ||
userInfo.app_metadata?.avatar_url ||
"";
// Configura estado inicial com o que tem no cache
setUserData({
id: userInfo.id ?? "",
email: userInfo.email ?? "",
@ -91,20 +112,62 @@ export default function Sidebar({ children }: SidebarProps) {
user_metadata: {
cpf: userInfo.user_metadata?.cpf ?? "",
email_verified: userInfo.user_metadata?.email_verified ?? false,
full_name: userInfo.user_metadata?.full_name ?? "",
full_name: userInfo.user_metadata?.full_name || userInfo.profile?.full_name || "Usuário",
phone_mobile: userInfo.user_metadata?.phone_mobile ?? "",
role: userInfo.user_metadata?.role ?? "",
avatar_url: rawAvatarPath,
},
identities:
userInfo.identities?.map((identity: any) => ({
identity_id: identity.identity_id ?? "",
id: identity.id ?? "",
user_id: identity.user_id ?? "",
provider: identity.provider ?? "",
})) ?? [],
identities: userInfo.identities ?? [],
is_anonymous: userInfo.is_anonymous ?? false,
});
setRole(userInfo.user_metadata?.role);
if (rawAvatarPath) {
setAvatarFullUrl(buildAvatarUrl(rawAvatarPath));
}
// 2. AUTO-REPARO: Se não tiver avatar ou profile no cache, busca na API e atualiza
if (!rawAvatarPath || !userInfo.profile) {
console.log("[Sidebar] Cache incompleto. Buscando dados frescos...");
usersService.getMe().then((freshData) => {
if (freshData && freshData.profile) {
const freshAvatar = freshData.profile.avatar_url;
// Atualiza o objeto local
const updatedUserInfo = {
...userInfo,
profile: freshData.profile, // Injeta o profile completo
user_metadata: {
...userInfo.user_metadata,
avatar_url: freshAvatar || userInfo.user_metadata.avatar_url
}
};
// Salva no localStorage para a próxima vez
localStorage.setItem("user_info", JSON.stringify(updatedUserInfo));
console.log("[Sidebar] LocalStorage sincronizado com sucesso.");
// Atualiza visualmente se achou um avatar novo
if (freshAvatar && freshAvatar !== rawAvatarPath) {
setAvatarFullUrl(buildAvatarUrl(freshAvatar));
// Atualiza o userData também para refletir no tooltip
setUserData(prev => prev ? ({
...prev,
user_metadata: {
...prev.user_metadata,
avatar_url: freshAvatar
}
}) : undefined);
}
}
}).catch(err => console.error("[Sidebar] Falha no auto-reparo:", err));
}
} catch (e) {
console.error("Erro ao processar dados do usuário na Sidebar:", e);
}
} else {
router.push("/login");
}
@ -129,6 +192,7 @@ export default function Sidebar({ children }: SidebarProps) {
try {
await api.logout();
} catch (error) {
console.error("Erro ao fazer logout", error);
} finally {
localStorage.removeItem("user_info");
localStorage.removeItem("token");
@ -212,6 +276,7 @@ export default function Sidebar({ children }: SidebarProps) {
};
const menuItems = SetMenuItems(role);
const isDefaultMode = theme === "light" && contrast === "normal";
if (!userData) {
return (
@ -222,17 +287,17 @@ export default function Sidebar({ children }: SidebarProps) {
}
return (
<div className="min-h-screen bg-gray-50 flex">
<div className="min-h-screen bg-background flex">
<div
className={`fixed top-0 h-screen flex flex-col z-30 transition-all duration-300
${sidebarCollapsed ? "w-16" : "w-64"}
bg-[#123965] text-white`}
${isDefaultMode ? "bg-[#123965] text-white" : "bg-sidebar text-sidebar-foreground"}`}
>
{/* TOPO */}
<div className="p-4 border-b border-white/10 flex items-center justify-between">
<div className={`p-4 border-b ${isDefaultMode ? "border-white/10" : "border-sidebar-border"} flex items-center justify-between`}>
{!sidebarCollapsed && (
<div className="flex items-center gap-2">
<div className="bg-white p-1 rounded-lg">
<div className="bg-background p-1 rounded-lg">
<img
src="/Logo MedConnect.png"
alt="Logo MedConnect"
@ -240,7 +305,7 @@ export default function Sidebar({ children }: SidebarProps) {
/>
</div>
<span className="font-semibold text-white text-lg">
<span className="font-semibold text-lg">
MedConnect
</span>
</div>
@ -250,7 +315,7 @@ export default function Sidebar({ children }: SidebarProps) {
variant="ghost"
size="sm"
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
className="p-1 text-white hover:bg-white/10 cursor-pointer"
className={`p-1 ${isDefaultMode ? "text-white hover:bg-white/10" : "hover:bg-sidebar-accent"} cursor-pointer`}
>
{sidebarCollapsed ? (
<ChevronRight className="w-5 h-5" />
@ -261,7 +326,7 @@ export default function Sidebar({ children }: SidebarProps) {
</div>
{/* MENU */}
<nav className="flex-1 p-3 overflow-y-auto">
<nav className="flex-1 px-3 py-6 overflow-y-auto flex flex-col gap-2">
{menuItems.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.href;
@ -270,11 +335,11 @@ export default function Sidebar({ children }: SidebarProps) {
<Link key={item.label} href={item.href}>
<div
className={`
flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors
flex items-center gap-3 px-3 py-2 rounded-lg transition-colors
${
isActive
? "bg-white/20 text-white font-semibold"
: "text-white/80 hover:bg-white/10 hover:text-white"
? `${isDefaultMode ? "bg-white/20 text-white font-semibold" : "bg-sidebar-primary text-sidebar-primary-foreground font-semibold"}`
: `${isDefaultMode ? "text-white/80 hover:bg-white/10 hover:text-white" : "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"}`
}
`}
>
@ -288,13 +353,21 @@ export default function Sidebar({ children }: SidebarProps) {
})}
</nav>
{/* PERFIL ORIGINAL + NOME BRANCO */}
<div className="mt-auto p-3 border-t border-white/10">
{/* PERFIL ORIGINAL + NOME BRANCO - CORREÇÃO DE ALINHAMENTO AQUI */}
<div
className={`
mt-auto p-3 border-t
${isDefaultMode ? "border-white/10" : "border-sidebar-border"}
flex flex-col
${sidebarCollapsed ? "items-center justify-center" : "items-stretch"}
`}
>
<SidebarUserSection
userData={userData}
sidebarCollapsed={sidebarCollapsed}
handleLogout={handleLogout}
isActive={role !== "paciente"}
avatarUrl={avatarFullUrl}
/>
</div>
</div>
@ -304,7 +377,6 @@ export default function Sidebar({ children }: SidebarProps) {
}`}
>
<main className="flex-1 p-4 md:p-6">{children}</main>
</div>
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
@ -325,7 +397,7 @@ export default function Sidebar({ children }: SidebarProps) {
</DialogFooter>
</DialogContent>
</Dialog>
 
</div>
</div>
);
}

View File

@ -19,12 +19,12 @@ import {
import { Textarea } from "@/components/ui/textarea";
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
import { format, addDays } from "date-fns";
import { User, StickyNote, Check, ChevronsUpDown } from "lucide-react";
import { User, StickyNote, CalendarDays, Stethoscope, Check, ChevronsUpDown } from "lucide-react";
import { smsService } from "@/services/Sms.mjs";
import { toast } from "@/hooks/use-toast";
import { cn } from "@/lib/utils";
// Componentes do Combobox (Barra de Pesquisa)
// --- Importações do Combobox ---
import {
Command,
CommandEmpty,
@ -40,19 +40,21 @@ import {
} from "@/components/ui/popover";
export default function ScheduleForm() {
// Estado do usuário e role
const [role, setRole] = useState<string>("paciente")
const [userId, setUserId] = useState<string | null>(null)
// --- ESTADOS ---
const [role, setRole] = useState<string>("paciente");
const [userId, setUserId] = useState<string | null>(null);
// Listas e seleções
// Estados de Paciente
const [patients, setPatients] = useState<any[]>([]);
const [selectedPatient, setSelectedPatient] = useState("");
const [openPatientCombobox, setOpenPatientCombobox] = useState(false);
// Estados de Médico
const [doctors, setDoctors] = useState<any[]>([]);
const [selectedDoctor, setSelectedDoctor] = useState("");
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false); // Novo estado para médico
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false);
// Estados de Agendamento
const [selectedDate, setSelectedDate] = useState("");
const [selectedTime, setSelectedTime] = useState("");
const [notes, setNotes] = useState("");
@ -60,187 +62,180 @@ export default function ScheduleForm() {
const [loadingDoctors, setLoadingDoctors] = useState(true);
const [loadingSlots, setLoadingSlots] = useState(false);
// Outras configs
const [tipoConsulta] = useState("presencial")
const [duracao] = useState("30")
const [disponibilidades, setDisponibilidades] = useState<any[]>([])
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({})
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null)
const calendarRef = useRef<HTMLDivElement | null>(null)
// Configurações
const [tipoConsulta] = useState("presencial");
const [duracao] = useState("30");
const [disponibilidades, setDisponibilidades] = useState<any[]>([]);
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({});
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);
// Funções auxiliares
const calendarRef = useRef<HTMLDivElement | null>(null);
// --- HELPER FUNCTIONS ---
const getWeekdayNumber = (weekday: string) =>
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].indexOf(weekday.toLowerCase()) + 1
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].indexOf(weekday.toLowerCase()) + 1;
const getBrazilDate = (date: Date) =>
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0))
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0));
// 🔹 Buscar dados do usuário e role
// --- EFFECTS ---
useEffect(() => {
;(async () => {
(async () => {
try {
const me = await usersService.getMe()
const currentRole = me?.roles?.[0] || "paciente"
setRole(currentRole)
setUserId(me?.user?.id || null)
const me = await usersService.getMe();
const currentRole = me?.roles?.[0] || "paciente";
setRole(currentRole);
setUserId(me?.user?.id || null);
if (["secretaria", "gestor", "admin"].includes(currentRole)) {
const pats = await patientsService.list()
setPatients(pats || [])
const pats = await patientsService.list();
setPatients(pats || []);
}
} catch (err) {
console.error("Erro ao carregar usuário:", err)
console.error("Erro ao carregar usuário:", err);
}
})()
}, [])
})();
}, []);
// 🔹 Buscar médicos
const fetchDoctors = useCallback(async () => {
setLoadingDoctors(true)
setLoadingDoctors(true);
try {
const data = await doctorsService.list()
setDoctors(data || [])
const data = await doctorsService.list();
setDoctors(data || []);
} catch (err) {
console.error("Erro ao buscar médicos:", err)
toast({ title: "Erro", description: "Não foi possível carregar médicos." })
console.error("Erro ao buscar médicos:", err);
toast({ title: "Erro", description: "Não foi possível carregar médicos." });
} finally {
setLoadingDoctors(false)
setLoadingDoctors(false);
}
}, [])
}, []);
useEffect(() => {
fetchDoctors()
}, [fetchDoctors])
fetchDoctors();
}, [fetchDoctors]);
// 🔹 Buscar disponibilidades
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
if (!doctorId) return
if (!doctorId) return;
try {
const disp = await AvailabilityService.listById(doctorId)
setDisponibilidades(disp || [])
await computeAvailabilityCountsPreview(doctorId, disp || [])
const disp = await AvailabilityService.listById(doctorId);
setDisponibilidades(disp || []);
await computeAvailabilityCountsPreview(doctorId, disp || []);
} catch (err) {
console.error("Erro ao buscar disponibilidades:", err)
setDisponibilidades([])
console.error("Erro ao buscar disponibilidades:", err);
setDisponibilidades([]);
}
}, [])
}, []);
const computeAvailabilityCountsPreview = async (
doctorId: string,
dispList: any[]
) => {
const computeAvailabilityCountsPreview = async (doctorId: string, dispList: any[]) => {
try {
const today = new Date()
const start = format(today, "yyyy-MM-dd")
const endDate = addDays(today, 90)
const end = format(endDate, "yyyy-MM-dd")
const today = new Date();
const start = format(today, "yyyy-MM-dd");
const endDate = addDays(today, 90);
const end = format(endDate, "yyyy-MM-dd");
const appointments = await appointmentsService.search_appointment(
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`,
)
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`
);
const apptsByDate: Record<string, number> = {}
;(appointments || []).forEach((a: any) => {
const d = String(a.scheduled_at).split("T")[0]
apptsByDate[d] = (apptsByDate[d] || 0) + 1
})
const apptsByDate: Record<string, number> = {};
(appointments || []).forEach((a: any) => {
const d = String(a.scheduled_at).split("T")[0];
apptsByDate[d] = (apptsByDate[d] || 0) + 1;
});
const counts: Record<string, number> = {}
const counts: Record<string, number> = {};
for (let i = 0; i <= 90; i++) {
const d = addDays(today, i)
const key = format(d, "yyyy-MM-dd")
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay()
const dailyDisp = dispList.filter((p) => getWeekdayNumber(p.weekday) === dayOfWeek)
const d = addDays(today, i);
const key = format(d, "yyyy-MM-dd");
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay();
const dailyDisp = dispList.filter((p) => getWeekdayNumber(p.weekday) === dayOfWeek);
if (dailyDisp.length === 0) {
counts[key] = 0
continue
counts[key] = 0;
continue;
}
let possible = 0
let possible = 0;
dailyDisp.forEach((p) => {
const [sh, sm] = p.start_time.split(":").map(Number)
const [eh, em] = p.end_time.split(":").map(Number)
const startMin = sh * 60 + sm
const endMin = eh * 60 + em
const slot = p.slot_minutes || 30
if (endMin >= startMin) possible += Math.floor((endMin - startMin) / slot) + 1
})
const occupied = apptsByDate[key] || 0
counts[key] = Math.max(0, possible - occupied)
const [sh, sm] = p.start_time.split(":").map(Number);
const [eh, em] = p.end_time.split(":").map(Number);
const startMin = sh * 60 + sm;
const endMin = eh * 60 + em;
const slot = p.slot_minutes || 30;
if (endMin >= startMin) possible += Math.floor((endMin - startMin) / slot) + 1;
});
const occupied = apptsByDate[key] || 0;
counts[key] = Math.max(0, possible - occupied);
}
setAvailabilityCounts(counts)
setAvailabilityCounts(counts);
} catch (err) {
console.error("Erro ao calcular contagens:", err)
setAvailabilityCounts({})
}
console.error("Erro ao calcular contagens:", err);
setAvailabilityCounts({});
}
};
// 🔹 Quando médico muda
useEffect(() => {
if (selectedDoctor) {
loadDoctorDisponibilidades(selectedDoctor)
loadDoctorDisponibilidades(selectedDoctor);
} else {
setDisponibilidades([])
setAvailabilityCounts({})
setDisponibilidades([]);
setAvailabilityCounts({});
}
setSelectedDate("")
setSelectedTime("")
setAvailableTimes([])
}, [selectedDoctor, loadDoctorDisponibilidades])
setSelectedDate("");
setSelectedTime("");
setAvailableTimes([]);
}, [selectedDoctor, loadDoctorDisponibilidades]);
// 🔹 Buscar horários disponíveis
const fetchAvailableSlots = useCallback(async (doctorId: string, date: string) => {
if (!doctorId || !date) return
setLoadingSlots(true)
setAvailableTimes([])
if (!doctorId || !date) return;
setLoadingSlots(true);
setAvailableTimes([]);
try {
const disponibilidades = await AvailabilityService.listById(doctorId)
const disponibilidades = await AvailabilityService.listById(doctorId);
const consultas = await appointmentsService.search_appointment(
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`,
)
const diaJS = new Date(date).getDay()
const diaAPI = diaJS === 0 ? 7 : diaJS
const disponibilidadeDia = disponibilidades.find((d: any) => getWeekdayNumber(d.weekday) === diaAPI)
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`
);
const diaJS = new Date(date).getDay();
const diaAPI = diaJS === 0 ? 7 : diaJS;
const disponibilidadeDia = disponibilidades.find((d: any) => getWeekdayNumber(d.weekday) === diaAPI);
if (!disponibilidadeDia) {
toast({ title: "Nenhuma disponibilidade", description: "Nenhum horário para este dia." })
return setAvailableTimes([])
toast({ title: "Nenhuma disponibilidade", description: "Nenhum horário para este dia." });
return setAvailableTimes([]);
}
const [startHour, startMin] = disponibilidadeDia.start_time.split(":").map(Number)
const [endHour, endMin] = disponibilidadeDia.end_time.split(":").map(Number)
const slot = disponibilidadeDia.slot_minutes || 30
const horariosGerados: string[] = []
let atual = new Date(date)
atual.setHours(startHour, startMin, 0, 0)
const end = new Date(date)
end.setHours(endHour, endMin, 0, 0)
const [startHour, startMin] = disponibilidadeDia.start_time.split(":").map(Number);
const [endHour, endMin] = disponibilidadeDia.end_time.split(":").map(Number);
const slot = disponibilidadeDia.slot_minutes || 30;
const horariosGerados: string[] = [];
let atual = new Date(date);
atual.setHours(startHour, startMin, 0, 0);
const end = new Date(date);
end.setHours(endHour, endMin, 0, 0);
while (atual <= end) {
horariosGerados.push(atual.toTimeString().slice(0, 5))
atual = new Date(atual.getTime() + slot * 60000)
horariosGerados.push(atual.toTimeString().slice(0, 5));
atual = new Date(atual.getTime() + slot * 60000);
}
const ocupados = (consultas || []).map((c: any) => String(c.scheduled_at).split("T")[1]?.slice(0, 5))
const livres = horariosGerados.filter((h) => !ocupados.includes(h))
setAvailableTimes(livres)
const ocupados = (consultas || []).map((c: any) => String(c.scheduled_at).split("T")[1]?.slice(0, 5));
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
setAvailableTimes(livres);
} catch (err) {
console.error(err)
toast({ title: "Erro", description: "Falha ao carregar horários." })
console.error(err);
toast({ title: "Erro", description: "Falha ao carregar horários." });
} finally {
setLoadingSlots(false)
setLoadingSlots(false);
}
}, [])
}, []);
useEffect(() => {
if (selectedDoctor && selectedDate) fetchAvailableSlots(selectedDoctor, selectedDate)
}, [selectedDoctor, selectedDate, fetchAvailableSlots])
if (selectedDoctor && selectedDate) fetchAvailableSlots(selectedDoctor, selectedDate);
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
// 🔹 Submeter agendamento
// --- SUBMIT ---
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role)
const patientId = isSecretaryLike ? selectedPatient : userId
e.preventDefault();
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
const patientId = isSecretaryLike ? selectedPatient : userId;
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." })
return
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
return;
}
try {
@ -251,66 +246,16 @@ export default function ScheduleForm() {
duration_minutes: Number(duracao),
notes,
appointment_type: tipoConsulta,
}
};
await appointmentsService.create(body);
const dateFormatted = selectedDate.split("-").reverse().join("/");
toast({
title: "Consulta agendada!",
description: `Consulta marcada para ${dateFormatted} às ${selectedTime} com o(a) médico(a) ${
doctors.find((d) => d.id === selectedDoctor)?.full_name || ""
}.`,
description: `Consulta marcada para ${dateFormatted} às ${selectedTime}.`,
});
let phoneNumber = "+5511999999999";
try {
if (isSecretaryLike) {
const patient = patients.find((p: any) => p.id === patientId)
const rawPhone = patient?.phone || patient?.phone_mobile || null
if (rawPhone) phoneNumber = rawPhone
} else {
const me = await usersService.getMe()
const rawPhone =
me?.profile?.phone ||
(typeof me?.profile === "object" && "phone_mobile" in me.profile
? (me.profile as any).phone_mobile
: null) ||
(typeof me === "object" && "user_metadata" in me ? (me as any).user_metadata?.phone : null) ||
null
if (rawPhone) phoneNumber = rawPhone
}
if (phoneNumber) {
phoneNumber = phoneNumber.replace(/\D/g, "")
if (!phoneNumber.startsWith("55")) phoneNumber = `55${phoneNumber}`
phoneNumber = `+${phoneNumber}`
}
console.log("📞 Telefone usado:", phoneNumber)
} catch (err) {
console.warn("⚠️ Não foi possível obter telefone do paciente:", err)
}
try {
const smsRes = await smsService.sendSms({
phone_number: phoneNumber,
message: `Lembrete: sua consulta é em ${dateFormatted} às ${selectedTime} na Clínica MediConnect.`,
patient_id: patientId,
})
if (smsRes?.success) {
console.log("✅ SMS enviado com sucesso:", smsRes.message_sid);
} else {
console.warn("⚠️ Falha no envio do SMS:", smsRes);
}
} catch (smsErr) {
console.error("❌ Erro ao enviar SMS:", smsErr);
}
// 🧹 limpa os campos
setSelectedDoctor("");
setSelectedDate("");
setSelectedTime("");
@ -322,234 +267,321 @@ export default function ScheduleForm() {
}
};
// 🔹 Tooltip no calendário
// --- TOOLTIP ---
useEffect(() => {
const cont = calendarRef.current
if (!cont) return
const cont = calendarRef.current;
if (!cont) return;
const onMove = (ev: MouseEvent) => {
const target = ev.target as HTMLElement | null
const btn = target?.closest("button")
if (!btn) return setTooltip(null)
const aria = btn.getAttribute("aria-label") || btn.textContent || ""
const parsed = new Date(aria)
if (isNaN(parsed.getTime())) return setTooltip(null)
const key = format(getBrazilDate(parsed), "yyyy-MM-dd")
const count = availabilityCounts[key] ?? 0
const target = ev.target as HTMLElement | null;
const btn = target?.closest("button");
if (!btn) return setTooltip(null);
const aria = btn.getAttribute("aria-label") || btn.textContent || "";
const parsed = new Date(aria);
if (isNaN(parsed.getTime())) return setTooltip(null);
const key = format(getBrazilDate(parsed), "yyyy-MM-dd");
const count = availabilityCounts[key] ?? 0;
setTooltip({
x: ev.pageX + 10,
y: ev.pageY + 10,
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
})
}
const onLeave = () => setTooltip(null)
cont.addEventListener("mousemove", onMove)
cont.addEventListener("mouseleave", onLeave)
});
};
const onLeave = () => setTooltip(null);
cont.addEventListener("mousemove", onMove);
cont.addEventListener("mouseleave", onLeave);
return () => {
cont.removeEventListener("mousemove", onMove)
cont.removeEventListener("mouseleave", onLeave)
}
}, [availabilityCounts])
cont.removeEventListener("mousemove", onMove);
cont.removeEventListener("mouseleave", onLeave);
};
}, [availabilityCounts]);
return (
<div className="py-3 px-2">
<div className="max-w-7xl mx-auto space-y-3">
<div className="w-full min-h-screen p-4 md:p-6 lg:p-8">
<div className="max-w-7xl mx-auto space-y-6">
<div className="space-y-1">
<h1 className="text-3xl font-bold text-slate-900">Agendar Consulta</h1>
<p className="text-slate-600">Selecione o médico, data e horário para sua consulta</p>
<h1 className="text-2xl md:text-3xl font-bold text-foreground">
Agendar Consulta
</h1>
<p className="text-muted-foreground text-sm md:text-base">
Preencha os dados abaixo para marcar seu horário.
</p>
</div>
<div className="grid lg:grid-cols-[1fr,380px] gap-4">
{/* Coluna do Formulário */}
<form onSubmit={handleSubmit} className="space-y-3">
<Card className="border shadow-sm">
<CardHeader className="pb-2">
<CardTitle className="text-lg">Informações Básicas</CardTitle>
<div className="grid grid-cols-1 xl:grid-cols-[1fr_350px] gap-6">
{/* == ESQUERDA == */}
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 items-start">
{/* BLOCO 1: SELEÇÃO */}
<Card className="h-full border shadow-sm">
<CardHeader className="pb-3 border-b bg-muted/20">
<CardTitle className="text-base flex items-center gap-2">
<Stethoscope className="w-4 h-4 text-primary" />
Dados da Consulta
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<CardContent className="space-y-5 pt-5">
{/* COMBOBOX DE PACIENTE */}
{["secretaria", "gestor", "admin"].includes(role) && (
<div className="space-y-2">
<Label htmlFor="patient-select" className="text-sm font-medium">
Paciente
</Label>
<Select value={selectedPatient} onValueChange={setSelectedPatient}>
<SelectTrigger id="patient-select">
<SelectValue placeholder="Selecione o paciente" />
</SelectTrigger>
<SelectContent>
<Label className="text-sm font-medium">Selecione o Paciente</Label>
<Popover open={openPatientCombobox} onOpenChange={setOpenPatientCombobox}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={openPatientCombobox}
className="w-full justify-between"
>
{selectedPatient
? patients.find((p) => p.id === selectedPatient)?.full_name
: "Buscar paciente..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
{/* AQUI: align="start" e w igual ao trigger garantem que não invada a lateral */}
<PopoverContent
className="w-[--radix-popover-trigger-width] min-w-0 p-0"
align="start"
side="bottom"
>
<Command>
<CommandInput placeholder="Procurar paciente..." />
{/* AQUI: max-h-[130px] no mobile deixa a lista bem compacta */}
<CommandList className="max-h-[130px] md:max-h-[300px] overflow-y-auto">
<CommandEmpty>Nenhum paciente encontrado.</CommandEmpty>
<CommandGroup>
{patients.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.full_name}
</SelectItem>
<CommandItem
key={p.id}
value={p.full_name}
onSelect={() => {
setSelectedPatient(p.id === selectedPatient ? "" : p.id);
setOpenPatientCombobox(false);
}}
className="text-xs md:text-sm py-1.5 md:py-2"
>
<Check
className={cn(
"mr-2 h-3 w-3 md:h-4 md:w-4",
selectedPatient === p.id ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{p.full_name}</span>
</CommandItem>
))}
</SelectContent>
</Select>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
)}
{/* COMBOBOX DE MÉDICO */}
<div className="space-y-2">
<Label htmlFor="doctor-select" className="text-sm font-medium">
Médico
</Label>
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
<SelectTrigger id="doctor-select">
<SelectValue placeholder="Selecione o médico" />
</SelectTrigger>
<SelectContent>
{loadingDoctors ? (
<SelectItem value="loading" disabled>
Carregando...
</SelectItem>
) : (
doctors
.slice() // evita mutar o state original
.sort((a, b) => a.full_name.localeCompare(b.full_name, "pt-BR"))
.map((d) => (
<SelectItem key={d.id} value={d.id}>
{d.full_name} {d.specialty}
</SelectItem>
))
)}
</SelectContent>
<Label className="text-sm font-medium">Selecione o Médico</Label>
</Select>
<Popover open={openDoctorCombobox} onOpenChange={setOpenDoctorCombobox}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={openDoctorCombobox}
className="w-full justify-between"
disabled={loadingDoctors}
>
{loadingDoctors ? "Carregando..." : (
selectedDoctor
? doctors.find((doctor) => doctor.id === selectedDoctor)?.full_name
: "Buscar médico..."
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
{/* AQUI: Configurações de largura e posicionamento corrigidos */}
<PopoverContent
className="w-[--radix-popover-trigger-width] min-w-0 p-0"
align="start"
side="bottom"
>
<Command>
<CommandInput placeholder="Procurar médico..." />
{/* AQUI: Altura reduzida no mobile */}
<CommandList className="max-h-[130px] md:max-h-[300px] overflow-y-auto">
<CommandEmpty>Nenhum médico encontrado.</CommandEmpty>
<CommandGroup>
{doctors.map((doctor) => (
<CommandItem
key={doctor.id}
value={doctor.full_name}
onSelect={() => {
setSelectedDoctor(doctor.id === selectedDoctor ? "" : doctor.id);
setOpenDoctorCombobox(false);
}}
className="text-xs md:text-sm py-1.5 md:py-2"
>
<Check
className={cn(
"mr-2 h-3 w-3 md:h-4 md:w-4",
selectedDoctor === doctor.id ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col truncate">
<span className="truncate font-medium">{doctor.full_name}</span>
<span className="text-[10px] md:text-xs text-muted-foreground truncate">{doctor.specialty}</span>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
<p className="text-xs text-muted-foreground mt-1">
Digite para filtrar por nome.
</p>
</div>
</CardContent>
</Card>
<Card className="border shadow-sm">
<CardHeader className="pb-2">
<CardTitle className="text-lg">Selecione a Data</CardTitle>
{/* BLOCO 2: CALENDÁRIO */}
<Card className="h-full border shadow-sm flex flex-col">
<CardHeader className="pb-3 border-b bg-muted/20">
<CardTitle className="text-base flex items-center gap-2">
<CalendarDays className="w-4 h-4 text-primary" />
Data Disponível
</CardTitle>
</CardHeader>
<CardContent>
<div ref={calendarRef} className="flex justify-center">
<CardContent className="flex-1 flex items-center justify-center pt-4 pb-4">
<div ref={calendarRef} className="flex justify-center w-full overflow-x-auto">
<CalendarShadcn
mode="single"
disabled={!selectedDoctor}
selected={
selectedDate
? new Date(selectedDate + "T12:00:00")
: undefined
}
selected={selectedDate ? new Date(selectedDate + "T12:00:00") : undefined}
onSelect={(date) => {
if (!date) return
const formatted = format(new Date(date.getTime() + 12 * 60 * 60 * 1000), "yyyy-MM-dd")
setSelectedDate(formatted)
if (!date) return;
const formatted = format(new Date(date.getTime() + 12 * 60 * 60 * 1000), "yyyy-MM-dd");
setSelectedDate(formatted);
}}
className="rounded-md"
className="rounded-md border p-3 w-fit"
/>
</div>
</CardContent>
</Card>
</div>
{/* BLOCO 3: OBSERVAÇÕES */}
<Card className="border shadow-sm">
<CardHeader className="pb-2">
<CardTitle className="text-lg">Observações (Opcional)</CardTitle>
<CardHeader className="pb-3 border-b bg-muted/20">
<CardTitle className="text-base flex items-center gap-2">
<StickyNote className="w-4 h-4 text-primary" />
Observações (Opcional)
</CardTitle>
</CardHeader>
<CardContent>
<CardContent className="pt-4">
<Textarea
placeholder="Adicione instruções ou informações importantes para o médico..."
placeholder="Instruções especiais, sintomas ou motivos da consulta..."
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={4}
className="resize-none"
rows={3}
className="resize-none w-full"
/>
</CardContent>
</Card>
</form>
</div>
<div className="space-y-3">
<Card className="border-2 border-blue-200 shadow-lg bg-gradient-to-br from-blue-50 to-white sticky top-6">
<CardHeader className="pb-3 border-b border-blue-100">
<CardTitle className="text-blue-900 flex items-center gap-2">
{/* == DIREITA == */}
<div className="w-full">
<div className="xl:sticky xl:top-6">
<Card className="border-2 border-primary shadow-lg h-full flex flex-col">
<CardHeader className="pb-4 border-b border-primary/20 bg-primary/5">
<CardTitle className="text-primary flex items-center gap-2 text-lg">
<User className="h-5 w-5" />
Resumo da Consulta
</CardTitle>
</CardHeader>
<CardContent className="pt-3 space-y-3">
<CardContent className="pt-6 space-y-5 flex-1">
<div className="grid grid-cols-2 gap-4 xl:grid-cols-1">
<div className="space-y-1">
<p className="text-xs font-medium text-slate-600">Médico</p>
<p className="text-sm font-semibold text-slate-900">
{selectedDoctor ? doctors.find((d) => d.id === selectedDoctor)?.full_name : "Não selecionado"}
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Médico</p>
<p className="text-sm font-semibold text-foreground break-words">
{selectedDoctor ? doctors.find((d) => d.id === selectedDoctor)?.full_name : ""}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-slate-600">Data</p>
<p className="text-sm font-semibold text-slate-900">
{selectedDate ? format(new Date(selectedDate + "T12:00:00"), "dd/MM/yyyy") : "Não selecionada"}
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Data</p>
<p className="text-sm font-semibold text-foreground">
{selectedDate ? format(new Date(selectedDate + "T12:00:00"), "dd/MM/yyyy") : ""}
</p>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="time-select" className="text-xs font-medium text-slate-600">
Horário
<div className="space-y-2 pt-2">
<Label htmlFor="time-select" className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
Horário da Sessão
</Label>
<Select
value={selectedTime}
onValueChange={setSelectedTime}
disabled={loadingSlots || availableTimes.length === 0}
>
<SelectTrigger id="time-select" className="bg-white">
<SelectTrigger id="time-select" className="bg-white w-full border-primary/30 focus:ring-primary">
<SelectValue
placeholder={
loadingSlots
? "Carregando..."
: availableTimes.length === 0
? "Nenhum horário"
: "Escolha o horário"
loadingSlots ? "Carregando..." : availableTimes.length === 0 ? "Selecione uma data" : "Escolha o horário"
}
/>
</SelectTrigger>
<SelectContent>
{availableTimes.map((h) => (
<SelectItem key={h} value={h}>
{h}
</SelectItem>
<SelectItem key={h} value={h}>{h}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="pt-3 border-t border-blue-100 space-y-2">
<div className="flex justify-between text-xs">
<span className="text-slate-600">Tipo:</span>
<span className="font-medium text-slate-900 capitalize">{tipoConsulta}</span>
<div className="pt-4 border-t border-dashed space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Tipo:</span>
<span className="font-medium capitalize">{tipoConsulta}</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-600">Duração:</span>
<span className="font-medium text-slate-900">{duracao} minutos</span>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Duração estimada:</span>
<span className="font-medium">{duracao} min</span>
</div>
</div>
{notes && (
<div className="pt-3 border-t border-blue-100">
<div className="flex items-start gap-2">
<StickyNote className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
<p className="text-xs italic text-slate-700 line-clamp-3">{notes}</p>
</div>
</div>
)}
<div className="pt-2 space-y-2">
<div className="pt-4 space-y-3 mt-auto">
<Button
type="submit"
onClick={handleSubmit}
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium shadow-md"
className="w-full bg-primary hover:bg-primary/90 text-primary-foreground font-semibold shadow-md py-6 h-auto text-base transition-all"
disabled={!selectedDoctor || !selectedDate || !selectedTime}
>
Confirmar Agendamento
</Button>
<Button
type="button"
variant="outline"
variant="ghost"
onClick={() => {
setSelectedDoctor("")
setSelectedDate("")
setSelectedTime("")
setNotes("")
setSelectedPatient("")
setSelectedDoctor("");
setSelectedDate("");
setSelectedTime("");
setNotes("");
setSelectedPatient("");
}}
className="w-full"
className="w-full text-muted-foreground hover:text-destructive"
>
Limpar Formulário
</Button>
@ -558,6 +590,8 @@ export default function ScheduleForm() {
</Card>
</div>
</div>
</div>
</div>
{tooltip && (
@ -580,5 +614,5 @@ export default function ScheduleForm() {
</div>
)}
</div>
)
);
}

View File

@ -76,23 +76,23 @@ export default function WeeklyScheduleCard({ doctorId }: WeeklyScheduleProps) {
return (
<div className="space-y-4 grid md:grid-cols-7 gap-2">
{loading ? (
<p className="text-sm text-gray-500 col-span-7 text-center">Carregando...</p>
<p className="text-sm text-muted-foreground col-span-7 text-center">Carregando...</p>
) : (
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "Saturday"].map((day) => {
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
const times = schedule[day] || [];
return (
<div key={day} className="space-y-4">
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
<div className="flex flex-col items-center justify-between p-3 bg-primary/10 rounded-lg">
<p className="font-medium capitalize text-foreground">{weekdaysPT[day]}</p>
<div className="text-center">
{times.length > 0 ? (
times.map((t, i) => (
<p key={i} className="text-sm text-gray-600">
<p key={i} className="text-sm text-muted-foreground">
{formatTime(t.start)} <br /> {formatTime(t.end)}
</p>
))
) : (
<p className="text-sm text-gray-400 italic">Sem horário</p>
<p className="text-sm text-muted-foreground italic">Sem horário</p>
)}
</div>
</div>

View File

@ -53,16 +53,16 @@ export function FilterBar({
Object.values(activeFilters).some(val => val !== "all" && val !== "");
return (
<div className={`flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200 ${className}`}>
<div className={`flex flex-col md:flex-row items-start md:items-center gap-3 bg-card p-4 rounded-lg border ${className}`}>
{/* Barra de Pesquisa */}
<div className="relative w-full md:flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder={searchPlaceholder}
value={searchTerm}
onChange={(e) => onSearch(e.target.value)}
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
className="pl-10 w-full bg-muted border-border focus:bg-card transition-colors"
/>
</div>
@ -100,7 +100,7 @@ export function FilterBar({
variant="ghost"
size="icon"
onClick={onClearFilters}
className="text-gray-500 hover:text-red-600"
className="text-muted-foreground hover:text-destructive"
title="Limpar filtros"
>
<X className="h-4 w-4" />

View File

@ -45,10 +45,10 @@ export function PatientDetailsModal({
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95%] sm:max-w-lg max-h-[90vh] overflow-y-auto">
<DialogContent className="max-w-[95%] sm:max-w-lg max-h-[90vh] overflow-y-auto bg-card text-card-foreground border border-border">
<DialogHeader>
<DialogTitle className="text-xl font-bold">Detalhes do Paciente</DialogTitle>
<DialogDescription>
<DialogTitle className="text-xl font-bold text-foreground">Detalhes do Paciente</DialogTitle>
<DialogDescription className="text-muted-foreground">
Informações detalhadas sobre o paciente.
</DialogDescription>
</DialogHeader>
@ -57,80 +57,80 @@ export function PatientDetailsModal({
{/* Grid Principal */}
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<p className="font-semibold text-gray-900">Nome Completo</p>
<p className="text-gray-700">{patient.nome}</p>
<p className="font-semibold text-foreground">Nome Completo</p>
<p className="text-muted-foreground">{patient.nome}</p>
</div>
{/* CORREÇÃO AQUI: Adicionado 'break-all' para quebrar o email */}
<div>
<p className="font-semibold text-gray-900">Email</p>
<p className="text-gray-700 break-all">{patient.email || "N/A"}</p>
<p className="font-semibold text-foreground">Email</p>
<p className="text-muted-foreground break-all">{patient.email || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Telefone</p>
<p className="text-gray-700">{patient.telefone}</p>
<p className="font-semibold text-foreground">Telefone</p>
<p className="text-muted-foreground">{patient.telefone}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Data de Nascimento</p>
<p className="text-gray-700">{patient.birth_date || "N/A"}</p>
<p className="font-semibold text-foreground">Data de Nascimento</p>
<p className="text-muted-foreground">{patient.birth_date || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">CPF</p>
<p className="text-gray-700">{patient.cpf || "N/A"}</p>
<p className="font-semibold text-foreground">CPF</p>
<p className="text-muted-foreground">{patient.cpf || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Tipo Sanguíneo</p>
<p className="text-gray-700">{patient.blood_type || "N/A"}</p>
<p className="font-semibold text-foreground">Tipo Sanguíneo</p>
<p className="text-muted-foreground">{patient.blood_type || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Peso (kg)</p>
<p className="text-gray-700">{patient.weight_kg || "0"}</p>
<p className="font-semibold text-foreground">Peso (kg)</p>
<p className="text-muted-foreground">{patient.weight_kg || "0"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Altura (m)</p>
<p className="text-gray-700">{patient.height_m || "0"}</p>
<p className="font-semibold text-foreground">Altura (m)</p>
<p className="text-muted-foreground">{patient.height_m || "0"}</p>
</div>
</div>
<hr className="border-gray-200" />
<hr className="border-border" />
{/* Seção de Endereço */}
<div>
<h4 className="font-semibold mb-3 text-gray-900">Endereço</h4>
<h4 className="font-semibold mb-3 text-foreground">Endereço</h4>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<p className="font-semibold text-gray-900">Rua</p>
<p className="text-gray-700">
<p className="font-semibold text-foreground">Rua</p>
<p className="text-muted-foreground">
{patient.street && patient.street !== "N/A"
? `${patient.street}, ${patient.number || ""}`
: "N/A"}
</p>
</div>
<div>
<p className="font-semibold text-gray-900">Complemento</p>
<p className="text-gray-700">{patient.complement || "N/A"}</p>
<p className="font-semibold text-foreground">Complemento</p>
<p className="text-muted-foreground">{patient.complement || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Bairro</p>
<p className="text-gray-700">{patient.neighborhood || "N/A"}</p>
<p className="font-semibold text-foreground">Bairro</p>
<p className="text-muted-foreground">{patient.neighborhood || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Cidade</p>
<p className="text-gray-700">{patient.cidade || "N/A"}</p>
<p className="font-semibold text-foreground">Cidade</p>
<p className="text-muted-foreground">{patient.cidade || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">Estado</p>
<p className="text-gray-700">{patient.estado || "N/A"}</p>
<p className="font-semibold text-foreground">Estado</p>
<p className="text-muted-foreground">{patient.estado || "N/A"}</p>
</div>
<div>
<p className="font-semibold text-gray-900">CEP</p>
<p className="text-gray-700">{patient.cep || "N/A"}</p>
<p className="font-semibold text-foreground">CEP</p>
<p className="text-muted-foreground">{patient.cep || "N/A"}</p>
</div>
</div>
</div>

View File

@ -33,6 +33,7 @@ interface Props {
sidebarCollapsed: boolean;
handleLogout: () => void;
isActive: boolean;
avatarUrl?: string;
}
export default function SidebarUserSection({
@ -40,6 +41,7 @@ export default function SidebarUserSection({
sidebarCollapsed,
handleLogout,
isActive,
avatarUrl,
}: Props) {
const pathname = usePathname();
const menuItems: any[] = [
@ -56,6 +58,18 @@ export default function SidebarUserSection({
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
];
// Função auxiliar para obter iniciais
const getInitials = (name: string) => {
if (!name) return "U";
return name
.split(" ")
.map((n) => n[0])
.slice(0, 2)
.join("")
.toUpperCase();
};
return (
<div className="border-t p-4 mt-auto">
{/* POPUP DE INFORMAÇÕES DO USUÁRIO */}
@ -67,12 +81,13 @@ export default function SidebarUserSection({
}`}
>
<Avatar>
<AvatarImage src="/placeholder.svg?height=40&width=40" />
<AvatarFallback>
{userData.user_metadata.full_name
.split(" ")
.map((n) => n[0])
.join("")}
<AvatarImage
src={avatarUrl}
alt={userData.user_metadata.full_name}
className="object-cover"
/>
<AvatarFallback className="text-black bg-gray-200 font-semibold">
{getInitials(userData.user_metadata.full_name)}
</AvatarFallback>
</Avatar>
@ -93,7 +108,7 @@ export default function SidebarUserSection({
<PopoverContent
align="center"
side="top"
className="w-64 p-4 shadow-lg border bg-white"
className="w-64 p-4 shadow-2xl border-2 border-primary/20 bg-card text-card-foreground ring-1 ring-primary/10"
>
<nav>
{menuItems.map((item) => {
@ -104,8 +119,8 @@ export default function SidebarUserSection({
<div
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
isActive
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
: "text-gray-600 hover:bg-gray-50"
? "bg-primary/10 text-primary border-r-2 border-primary"
: "text-foreground hover:bg-muted"
}`}
>
<Icon className="w-5 h-5 flex-shrink-0" />
@ -125,19 +140,19 @@ export default function SidebarUserSection({
size="sm"
className={
sidebarCollapsed
? "w-full bg-white text-black flex justify-center items-center p-2 hover:bg-gray-200"
: "w-full bg-white text-black hover:bg-gray-200 cursor-pointer"
? "w-full bg-card text-foreground border-2 border-border flex justify-center items-center p-2 hover:bg-muted"
: "w-full bg-card text-foreground border-2 border-border hover:bg-muted cursor-pointer"
}
onClick={handleLogout}
>
<LogOut
className={
sidebarCollapsed ? "h-5 w-5 text-black" : "mr-2 h-4 w-4 text-black"
sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"
}
/>
{!sidebarCollapsed && "Sair"}
</Button>
   
</div>
);
}

View File

@ -18,7 +18,9 @@ interface UseAuthLayoutOptions {
requiredRole?: string[];
}
export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
export function useAuthLayout(
{ requiredRole }: UseAuthLayoutOptions = {}
) {
const [user, setUser] = useState<UserLayoutData | null>(null);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
@ -28,8 +30,16 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
try {
const fullUserData = await usersService.getMe();
if (!fullUserData.roles.some((role) => requiredRole?.includes(role))) {
console.error(`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`);
// só verifica papel se requiredRole existir
if (
requiredRole &&
!fullUserData.roles.some((role: string) =>
requiredRole.includes(role)
)
) {
console.error(
`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`
);
toast({
title: "Acesso Negado",
description: "Você não tem permissão para acessar esta página.",
@ -40,10 +50,9 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
}
const avatarPath = fullUserData.profile.avatar_url;
// *** A CORREÇÃO ESTÁ AQUI ***
// Adicionamos o nome do bucket 'avatars' na URL final.
const avatarFullUrl = avatarPath ? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}` : undefined;
const avatarFullUrl = avatarPath
? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}`
: undefined;
setUser({
id: fullUserData.user.id,
@ -51,7 +60,7 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
email: fullUserData.user.email,
roles: fullUserData.roles,
avatar_url: avatarPath,
avatarFullUrl: avatarFullUrl,
avatarFullUrl,
});
} catch (error) {
console.error("Falha na autenticação do layout:", error);
@ -62,7 +71,7 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
};
fetchUserData();
}, [router, requiredRole]);
}, [router]); // não depende mais de requiredRole
return { user, isLoading };
}

View File

@ -2,7 +2,11 @@ import { api } from "./api.mjs";
export const patientsService = {
list: () => api.get("/rest/v1/patients"),
getById: (id) => api.get(`/rest/v1/patients?id=eq.${id}`),
getById: (id) => {
console.log("getById chamado", id);
return api.get(`/rest/v1/patients?id=eq.${id}`);
},
create: (data) => api.post("/rest/v1/patients", data),
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),

View File

@ -3,6 +3,7 @@ import { api } from "./api.mjs";
export const usersService = {
// Função getMe corrigida para chamar a si mesma pelo nome
async getMe() {
console.log("getMe chamado");
const sessionData = await api.getSession();
if (!sessionData?.id) {
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);