import React, { FC, useEffect, useState } from "react";
import { Content } from "../components";
import { apiCall } from "../../untils/apiCall";
import { useStoreState } from "../../store";
import { LoadingContent } from "../layouts/Loading";
import { t } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { PaymentTemplate } from "./Partial/PaymentTemplate";
import { MEMBER_ROLE } from "../../definitions/organizations";

export const PaymentError: FC = () => {
  useEffect(() => {
    sessionStorage.removeItem("paymentFlow");
  }, []);

  const { orgRole, orgID } = useStoreState((state) => state.user.userDetails);

  const [pageData, setPageData] = useState({
    loading: false,
    stripeCustomerID: "",
  });

  useEffect(() => {
    if (orgRole === MEMBER_ROLE.admin) {
      setPageData((prev) => ({ ...prev, loading: true }));

      const options = {
        orgID: orgID,
      };
      apiCall("organization/getCustomerID", options, (response: any) => {
        setPageData((prev) => ({
          ...prev,
          loading: false,
          stripeCustomerID: response.customerId,
        }));
      });
    }
  }, [orgRole, orgID]);

  const handleClick = async () => {
    const options = {
      customerId: pageData.stripeCustomerID,
    };
    await apiCall(
      "organization/getPortalAddress",
      options,
      (response: any) => {
        const portalUrl = response.url;
        window.location.href = portalUrl;
      },
    );
  };

  return (
    <Content>
      {pageData.loading ? (
        <LoadingContent />
      ) : (
        <PaymentTemplate
          title={t(dictionary.paymentTitleFail)}
          content={
            orgRole === MEMBER_ROLE.admin
              ? t(dictionary.paymentContentFail)
              : t(dictionary.errorPaymentUser)
          }
          isAdmin={orgRole === MEMBER_ROLE.admin}
          onClick={handleClick}
          butonLabel={t(dictionary.errorPaymentAction)}
        />
      )}
    </Content>
  );
};
