import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { apiPost } from "../../../../lib/api/methods";
import { PACKAGES_ENDPOINTS } from "../endpoints";
import { errorToast, successToast } from "../../../../utils/toast";
import { SUCCESS_MESSAGES } from "./messages";


type CheckoutSession = {
  checkoutUrl: string;
  sessionId: string;
};

export default function useCreateCheckoutSession() {
  const [redirecting, setRedirecting] = useState(false);

  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["create-checkout-session"],
    mutationFn: async (data: { orderId: string; packageName: string }) => {
      const res = await apiPost<CheckoutSession>(
        PACKAGES_ENDPOINTS.PACKAGE_PAYMENT_SESSION,
        { packageOrderUuid: data.orderId },
      );

      return {
        checkoutUrl: res.data.checkoutUrl,
        sessionId: res.data.sessionId,
        packageName: data.packageName,
      };
    },
    onSuccess: (data) => {
      setRedirecting(true);
      successToast(SUCCESS_MESSAGES.CREATE_CHECKOUT);

      const { checkoutUrl, sessionId, packageName } = data;

      if (sessionId && packageName) {
        localStorage.setItem(sessionId, packageName);
      }

      window.location.assign(checkoutUrl);
    },
    onError: (error: any) => {
      setRedirecting(false);

      errorToast(
        error?.response?.data?.message ?? "Failed to create checkout session.",
      );
    },
  });

  return {
    handleCheckoutSession: mutateAsync,
    loading: isPending || redirecting,
  };
}
