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

export const PaymentMiss: FC = () => {
  const { orgRole, email, orgID, lang } = useStoreState(
    (state) => state.user.userDetails,
  );

  const [pageData, setPageData] = useState({
    loading: true,
    subscriptionID: "",
    subscriptionEndDate: 0,
    stripeCustomerID: "",
    fakturowniaCustomerID: "",
    keyPlan: "",
  });

  useEffect(() => {
    const getOrgSettings = async () => {
      const options = { orgID };
      await apiCall("user/getOrgSettings", options, (response: any) => {
        setPageData((prev) => ({
          ...prev,
          ...response.orgDetails,
          loading: false,
        }));
      });
    };
    getOrgSettings();
  }, [orgID]);

  const handleClick = async () => {
    setPageData((prev) => ({ ...prev, loading: true }));
    if (orgRole === "admin") {
      const options = {
        email,
        orgID,
        stripeUserID: pageData.stripeCustomerID,
        produktKey: pageData.keyPlan,
        fakturowniaCustomerID: pageData.fakturowniaCustomerID,
      };
      await apiCall("user/recreacteSubsciption", options, (response: any) => {
        window.location.href = response.session.url;
      });
    }
  };
  return (
    <ContentFull>
      {pageData.loading ? (
        <LoadingContent />
      ) : (
        <PaymentTemplate
          title={t(dictionary.paymentTitleMissed)}
          content={
            orgRole === MEMBER_ROLE.admin
              ? t(dictionary.finishSubskrypcjeAdmin)
              : t(dictionary.finishSubskrypcjeUser)
          }
          isAdmin={orgRole === MEMBER_ROLE.admin}
          onClick={handleClick}
          butonLabel={t(dictionary.finishSubsrybcionAction)}
        />
      )}
    </ContentFull>
  );
};
