import { useState } from 'react';
import { ChannelManagerService } from '@/services/channelManagerApi';

export interface BookingData {
  listingId: string;
  guestName: string;
  guestEmail: string;
  guestPhone: string;
  checkIn: string;
  checkOut?: string;
  guests: number;
  totalAmount: number;
  specialRequests?: string;
}

export const useBooking = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const createBooking = async (bookingData: BookingData) => {
    try {
      setLoading(true);
      setError(null);

      const reservationData = {
        ...bookingData,
        status: 'pending',
        paymentStatus: 'pending',
        channel: 'direct',
        createdAt: new Date().toISOString(),
      };

      const response = await ChannelManagerService.createReservation(reservationData);
      return { success: true, data: response };
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Error al crear la reserva';
      setError(errorMessage);
      return { success: false, error: errorMessage };
    } finally {
      setLoading(false);
    }
  };

  const checkAvailability = async (listingId: string, startDate: string, endDate?: string) => {
    try {
      setLoading(true);
      setError(null);

      // This would call the API to check availability
      // For now, returning true as placeholder
      return { success: true, available: true };
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Error al verificar disponibilidad';
      setError(errorMessage);
      return { success: false, available: false, error: errorMessage };
    } finally {
      setLoading(false);
    }
  };

  const clearError = () => {
    setError(null);
  };

  return {
    loading,
    error,
    createBooking,
    checkAvailability,
    clearError,
  };
};

export default useBooking;
