'use client';
import { GetEventoWithCuestionariosWithCupos } from '@/types/evento';
import axiosInstance from '@/utils/api-config';
import {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
  ReactNode,
} from 'react';

interface EventoContextType {
  evento: GetEventoWithCuestionariosWithCupos | null;
  loading: boolean;
  error: string | null;
  refetch: () => void;
  updateEvento: (
    eventoData: Partial<GetEventoWithCuestionariosWithCupos>
  ) => void;
  setEventoData: (evento: GetEventoWithCuestionariosWithCupos) => void;
}

const EventoContext = createContext<EventoContextType | undefined>(undefined);

interface EventoProviderProps {
  children: ReactNode;
  id_evento: string;
}

export function EventoProvider({ children, id_evento }: EventoProviderProps) {
  const [evento, setEvento] =
    useState<GetEventoWithCuestionariosWithCupos | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchEvento = useCallback(async () => {
    console.log('Fetching evento with ID:', id_evento);
    try {
      setLoading(true);
      setError(null);
      const response =
        await axiosInstance.get<GetEventoWithCuestionariosWithCupos>(
          `/evento/${id_evento}/cuestionarios`
        );
      setEvento(response.data);
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : 'Error al cargar el evento';
      setError(errorMessage);
      console.error('Error fetching evento:', error);
    } finally {
      setLoading(false);
    }
  }, [id_evento]);

  useEffect(() => {
    if (id_evento) {
      fetchEvento();
    }
  }, [id_evento, fetchEvento]);

  const refetch = () => {
    fetchEvento();
  };

  const updateEvento = useCallback(
    (eventoData: Partial<GetEventoWithCuestionariosWithCupos>) => {
      setEvento((prev) => (prev ? { ...prev, ...eventoData } : null));
    },
    []
  );

  const setEventoData = useCallback(
    (newEvento: GetEventoWithCuestionariosWithCupos) => {
      setEvento(newEvento);
    },
    []
  );

  const value: EventoContextType = {
    evento,
    loading,
    error,
    refetch,
    updateEvento,
    setEventoData,
  };

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

export function useEvento() {
  const context = useContext(EventoContext);
  if (context === undefined) {
    throw new Error('useEvento must be used within an EventoProvider');
  }
  return context;
}
