import { useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { getSalesServiceV1 } from "services";
import {
  DataStripeAccountLink,
  StripeAccountLinkBody,
} from "@komi-app/sales-sdk";
import notification from "utils/notification";
import { useQuery } from "hooks/useQuery";

export const StripeRefreshUrl = () => {
  const query = useQuery();

  const payload: StripeAccountLinkBody = {
    accountId: query.get("accountId") ?? "",
    returnUrl: `${window.location.origin}/admin/settings/subscription`,
    refreshUrl: `${window.location.href}`,
  };

  const { mutate: generateAccountLink } =
    useMutation({
      mutationFn: () => getSalesServiceV1().generateStripeAccountLink(payload),
      onSuccess: (response: DataStripeAccountLink) => {
        window.open(response.accountLinkUrl, "_blank");
      },
      onError: () => {
        notification.error({
          message:
            "Something went wrong and we couldn't connect your Stripe account. Try again.",
        });
      },
    });

  useEffect(() => {
    generateAccountLink();
  }, [generateAccountLink]);

  return null;
};
