"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<void>;
  addAppointment: (appointmentData: Omit<Appointment, 'id' | 'status'>) => Promise<void>;
  updateAppointment: (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => Promise<void>;
  deleteAppointment: (appointmentId: string) => 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 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<Appointment, 'id' | 'status'>) => {
    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<Omit<Appointment, 'id'>>) => {
    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 (
    <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;
}