import {
  PaymentElement,
  useElements,
  useStripe,
} from "@stripe/react-stripe-js";
import { useStateMachine } from "little-state-machine";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import Button from "../../../../shared/components/Button";
import Typography from "../../../../shared/components/Typography";
import { updateStripeSub } from "../../../../shared/services/updateSubcription";
import updateCheckoutState from "../../../../shared/utilities/updateCheckoutState";

interface PaymentFormProps {}

const PaymentForm: React.FC<PaymentFormProps> = () => {
  const stripe = useStripe();
  const elements = useElements();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>("");
  const { state, actions } = useStateMachine({
    updateCheckoutState,
  });

  const { t } = useTranslation();

  const handleSubmit = async (event: React.FormEvent) => {
    // We don't want to let default form submission happen here,
    // which would refresh the page.
    event.preventDefault();

    if (!stripe || !elements) {
      // Stripe.js has not yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return;
    }

    setIsLoading(true);
    setErrorMessage("");

    const result = await stripe
      .confirmPayment({
        //`Elements` instance that was used to create the Payment Element
        elements,
        confirmParams: {
          return_url: "https://example.com",
        },
        redirect: "if_required",
      })
      .then((response) => {
        let paymentIntent = response.paymentIntent;
        if (
          state.stripe.subscriptionId &&
          state.stripe.customerId &&
          paymentIntent &&
          paymentIntent.payment_method
        ) {
          updateStripeSub({
            subcriptionId: state.stripe.subscriptionId,
            customerId: state.stripe.customerId,
            payment_method: paymentIntent.payment_method,
          }).then((res) => {
            console.log("update subscription success--->", res);
          });

          if (paymentIntent.status === "succeeded") {
            window.location.href =
              process.env.REACT_APP_PUBLIC_URL +
              "/confirmation?redirect_status=succeeded";
          }
        }
        if (response.error) {
          setErrorMessage(response.error?.message || t("Something went wrong"));
        }
      })
      .finally(() => setIsLoading(false));
  };

  return (
    <div className="mt-5">
      <form onSubmit={handleSubmit}>
        <PaymentElement />

        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <Button
            loading={isLoading || !stripe || !elements}
            type="submit"
            className="mt-5"
          >
            {t("Subscribe")}
          </Button>
        </div>
        {errorMessage && (
          <Typography appearance="error" className="mt-5">
            {t(errorMessage)}
          </Typography>
        )}
      </form>
    </div>
  );
};

export default PaymentForm;
