'use client';

import React, { createContext, useContext, useState, ReactNode } from 'react';
import { Volunteer } from '@/types/volunteer';

interface VolunteersContextType {
  volunteers: Volunteer[];
  setVolunteers: (volunteers: Volunteer[]) => void;
  getVolunteerById: (id: string) => Volunteer | null;
}

const VolunteersContext = createContext<VolunteersContextType | undefined>(undefined);

export const useVolunteers = () => {
  const context = useContext(VolunteersContext);
  if (!context) {
    throw new Error('useVolunteers must be used within a VolunteersProvider');
  }
  return context;
};

interface VolunteersProviderProps {
  children: ReactNode;
}

export const VolunteersProvider: React.FC<VolunteersProviderProps> = ({ children }) => {
  const [volunteers, setVolunteers] = useState<Volunteer[]>([]);

  const getVolunteerById = (id: string): Volunteer | null => {
    return volunteers.find(volunteer => volunteer._id === id) || null;
  };

  const value = {
    volunteers,
    setVolunteers,
    getVolunteerById,
  };

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