import React, { useState } from 'react';

import { StoreProduct } from '@medusajs/types';

import { getAvailableAppointmentsForService } from '~/lib/services/connected-online.service';

import { ServiceCategory } from '../service-categories';
import { BookingContext } from './booking.context';

export function useBooking() {
  const context = React.useContext(BookingContext);

  if (!context) {
    throw new Error('useBooking must be used within a BookingProvider.');
  }

  return context;
}

export const BookingProvider: React.FC<{
  children: React.ReactElement;
  category: ServiceCategory;
}> = ({ children, category }) => {
  const [selectedService, setSelectedService] = useState<StoreProduct | null>(
    category.products[0] || null,
  );
  const [timeSlots, setTimeSlots] = useState<string[]>([]);

  const updateTimeSlots = async (serviceId: number) => {
    const response = await getAvailableAppointmentsForService(serviceId);
    console.log('updateTimeSlots response', response);
    // Fetch time slots based on the selected service ID
  };

  return (
    <BookingContext.Provider
      value={{
        timeSlots,
        selectedService,
        setSelectedService,
        updateTimeSlots,
      }}
    >
      {children}
    </BookingContext.Provider>
  );
};
