// Caminho: app/context/AppointmentsContext.tsx (Completo e Corrigido)
"use client";

import React, { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
import { agendamentosApi, Appointment, CreateAppointmentData } from '@/services/agendamentosApi';
import { usuariosApi, User } from '@/services/usuariosApi';
import { toast } from "sonner";

// As definições de componentes de UI foram REMOVIDAS deste arquivo.
// Elas pertencem aos arquivos que as utilizam, como `dashboard/page.tsx`.

export interface AppointmentsContextType {
  appointments: Appointment[];
  isLoading: boolean;
  error: string | null;
  fetchAppointments: () => Promise<void>;
  addAppointment: (appointmentData: CreateAppointmentData) => Promise<void>;
  updateAppointment: (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => Promise<void>;
}

const AppointmentsContext = createContext<AppointmentsContextType | undefined>(undefined);

export function AppointmentsProvider({ children }: { children: ReactNode }) {
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchAppointments = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const user = await usuariosApi.getCurrentUser();
      if (user?.id) {
        const data = await agendamentosApi.listByPatient(user.id);
        setAppointments(data || []);
      } else {
        setAppointments([]);
      }
    } 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: CreateAppointmentData) => {
    try {
      await agendamentosApi.create(appointmentData);
      await fetchAppointments();
    } catch (err) {
      console.error("Erro ao adicionar agendamento:", err);
      setError("Falha ao criar o novo agendamento. Tente novamente.");
      throw err;
    }
  };

  const updateAppointment = async (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => {
    try {
      toast.warning("Funcionalidade indisponível.", { description: "A API não suporta a atualização de agendamentos." });
    } catch (err) {
      console.error("Erro ao tentar atualizar agendamento:", err);
      setError("Falha ao atualizar o agendamento. Tente novamente.");
      throw err;
    }
  };

  const value = {
    appointments,
    isLoading,
    error,
    fetchAppointments,
    addAppointment,
    updateAppointment,
  };

  return (
    <AppointmentsContext.Provider value={value}>
      {children}
    </AppointmentsContext.Provider>
  );
}

export function useAppointments() {
  const context = useContext(AppointmentsContext);
  if (context === undefined) {
    throw new Error('useAppointments deve ser usado dentro de um AppointmentsProvider');
  }
  return context;
}