"use client"; import React, { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react'; import { agendamentosApi, Appointment } from '@/services/agendamentosApi'; export interface AppointmentsContextType { appointments: Appointment[]; isLoading: boolean; error: string | null; fetchAppointments: () => Promise; addAppointment: (appointmentData: Omit) => Promise; updateAppointment: (appointmentId: string, updatedData: Partial>) => Promise; deleteAppointment: (appointmentId: string) => Promise; } const AppointmentsContext = createContext(undefined); export function AppointmentsProvider({ children }: { children: ReactNode }) { const [appointments, setAppointments] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const fetchAppointments = useCallback(async () => { setIsLoading(true); setError(null); try { const data = await agendamentosApi.list(); setAppointments(data || []); } catch (err) { console.error("Erro ao buscar agendamentos:", err); setError("Não foi possível carregar os agendamentos."); setAppointments([]); } finally { setIsLoading(false); } }, []); useEffect(() => { fetchAppointments(); }, [fetchAppointments]); const addAppointment = async (appointmentData: Omit) => { try { await agendamentosApi.create(appointmentData); await fetchAppointments(); // Recarrega a lista para incluir o novo agendamento } catch (err) { console.error("Erro ao adicionar agendamento:", err); setError("Falha ao criar o novo agendamento. Tente novamente."); } }; const updateAppointment = async (appointmentId: string, updatedData: Partial>) => { try { await agendamentosApi.update(appointmentId, updatedData); await fetchAppointments(); // Recarrega a lista para refletir as alterações } catch (err) { console.error("Erro ao atualizar agendamento:", err); setError("Falha ao atualizar o agendamento. Tente novamente."); } }; const deleteAppointment = async (appointmentId: string) => { try { await agendamentosApi.delete(appointmentId); await fetchAppointments(); // Recarrega a lista para remover o item excluído } catch (err) { console.error("Erro ao excluir agendamento:", err); setError("Falha ao excluir o agendamento. Tente novamente."); } }; const value = { appointments, isLoading, error, fetchAppointments, addAppointment, updateAppointment, deleteAppointment, }; return ( {children} ); } export function useAppointments() { const context = useContext(AppointmentsContext); if (context === undefined) { throw new Error('useAppointments deve ser usado dentro de um AppointmentsProvider'); } return context; }