import { useState } from "react";
import { getCheckout } from "@/_lib/api/checkout";
import { useCheckoutResult } from "@/_types/Types";
import { useCartStore } from "@/_stores/useCartStore";

export function useCheckout(): useCheckoutResult {
  const [clientSecret, setClientSecret] = useState<null | string>(null);
  const [isCartEmpty, setIsCartEmpty] = useState<boolean>(false);
  const bookingData = useCartStore((state) => state.bookingData);
  const setBookingId = useCartStore((state) => state.setBookingId);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchCheckout = async (amount: number, currency: string) => {
    const subtotalValue = Number(amount) * 100;
    setIsCartEmpty(subtotalValue === 0);
    if (subtotalValue === 0) return;
    if (!bookingData) return;
    setLoading(true);
    setError(null);
    console.log("Fetching checkout with subtotal:", subtotalValue, "and currency:", currency);

    const body = {
      amount: subtotalValue,
      currency: currency,
      custom_data: null,
      booking_slot_id: bookingData?.slotId,
      language: bookingData?.language,
      locale: bookingData?.locale,
      exam_id: bookingData?.id,
    };

    try {
      const response = await getCheckout(body);
      setClientSecret(response.data.client_secret);
      setBookingId(response?.data?.booking?.id);
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message);
      } else {
        setError("An unknown error occurred");
      }
    } finally {
      setLoading(false);
    }
  };


  return { clientSecret, isCartEmpty, loading, error, fetchCheckout };
}
