import { useEffect, useState } from "react";
import { getUserBookings } from "@/_lib/api/bookings";
import { useConfirmationResult } from "@/_types/Types";
import { useCartStore } from "@/_stores/useCartStore";
import { Booking, StripePayment } from "@/_types/Types";

export function useConfirmation(): useConfirmationResult {
  const clearCart = useCartStore((state) => state.clearCart);

  const [booking, setBooking] = useState<Booking | null>(null);
  const [stripePayment, setStripePayment] = useState<StripePayment | null>(
    null
  );
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchConfirmation = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await getUserBookings();
      console.log(response, "response");
      const booking = response.data.booking;
      const stripePayment = response.data.stripe_payment;
      if (booking) {
        setBooking(booking);
        setStripePayment(stripePayment);
        setLoading(false);
        clearCart();
      }
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message);
      } else {
        setError("An unknown error occurred");
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConfirmation();
  });

  return {
    booking,
    stripePayment,
    loading,
    error,
    refetch: fetchConfirmation,
  };
}
