import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import ContentWrapper from "../ContentWrapper/ContentWrapper";
import FAQ from "../FAQ/FAQ";
import Footer from "../Footer/Footer";
import Header from "../Header/Header";
import { faqsPricing } from "../data/faqs";
import { createPurchase, getAkademyClasses, getAkademyPlans, updatePurchase } from "../redux/purchaseSlice";
import { getFormattedCurrencyWithoutDecimals } from "../utils";
import ProductCard from "./components/ProductCard/ProductCard";
import ProductCardHorizontal from "./components/ProductCardHorizontal/ProductCardHorizontal";
import Tab from "./components/Tab/Tab";
import { educatorProducts, educatorProductsUSD, parentProducts, parentProductsUSD, schoolProducts, schoolProductsUSD } from "./config";
import style from "./ProductPricingPage.module.css";

const tabList = [
  { id: 3, text: "SCHOOLS", productCategory: "ENTERPRISE_SCHOOL" },
  { id: 2, text: "EDUCATORS", productCategory: "TUTION_EDUCATOR" },
  { id: 1, text: "PARENTS", productCategory: "RETAIL_PARENT" },
];

function ProductPricingPage() {
  const dispatch = useDispatch();
  window.scrollTo({ top: 0, behavior: "instant" });

  const { planPriceDetails, classes, purchaseId, currency } = useSelector(
    ({ purchase }) => {
      return {
        planPriceDetails: purchase.planPriceDetails,
        classes: purchase.classes,
        purchaseId: purchase.purchaseId,
        currency: purchase.currency,
      };
    }
  );

  const [tab, setTab] = useState(tabList[0]);
  const [config, setConfig] = useState({
    RETAIL_PARENT: localStorage.getItem("currency")
      ? parentProductsUSD
      : parentProducts,
    TUTION_EDUCATOR: localStorage.getItem("currency")
      ? educatorProductsUSD
      : educatorProducts,
    ENTERPRISE_SCHOOL: localStorage.getItem("currency")
      ? schoolProductsUSD
      : schoolProducts,
  });

  useEffect(() => {
    dispatch(getAkademyPlans());
    dispatch(getAkademyClasses());
  }, []);

  const handleAddToCart = (props) => {
    console.log(props);

    const payload = {
      currency,
      cartItem: { planId: props.planId, planVariantIdx: props.priceIdx },
    };

    if (props.classIdx >= 0)
      payload.cartItem.classId = classes[props.classIdx]._id;

    if (
      tab.productCategory === "TUTION_EDUCATOR" ||
      tab.productCategory === "ENTERPRISE_SCHOOL"
    )
      payload.cartItem.additionalLicenses = [
        {
          licenseQuotaType: "GENERAL",
          count: 1,
          classId:
            props.classIdx >= 0 ? classes[props.classIdx]._id : undefined,
        },
      ];

    if (!purchaseId)
      dispatch(createPurchase())
        .unwrap()
        .then((res) => {
          addToCart(payload);
        });
    else addToCart(payload);
  };

  const addToCart = async (payload) => {
    dispatch(updatePurchase(payload))
      .unwrap()
      .then(() => {
        toast.success("Product added to Cart");
      })
      .catch((err) => {
        console.log(err);
        toast.error(err.message);
      });
  };

  useEffect(() => {
    if (!planPriceDetails || !classes) return;

    const newConfig = { ...config };
    Object.entries(planPriceDetails).map(
      ([productCategory, planDetailsMap]) => {
        Object.entries(planDetailsMap).map(([plan, planDetails]) => {
          if (!config[productCategory][plan]) return;

          newConfig[productCategory][plan].currency = currency;
          newConfig[productCategory][plan].planId = planDetails._id;
          newConfig[productCategory][plan].priceList = planDetails.variants
            .filter(({ priceDetails }) =>
              priceDetails.find(
                (priceDetail) => priceDetail.currency === currency
              )
            )
            .map(({ termInMonths, priceDetails }) => {
              let text = "";
              let text2 = null;
              let amount = 0;

              // if (productCategory === "RETAIL_PARENT") {
              // 	if (termInMonths === 12) text = "per year";
              // 	else if (termInMonths === 4) text = "per term";
              // } else if (productCategory === "TUTION_EDUCATOR") {
              // 	if (termInMonths === 12) text = "per seat / per year";
              // 	else if (termInMonths === 4) text = "per seat / per term";
              // } else if (productCategory === "ENTERPRISE_SCHOOL") {
              // 	if (termInMonths === 12) text = "per year";
              // 	else if (termInMonths === 4) text = "per term";
              // }

              if (termInMonths === 12) text = "per year";
              else if (termInMonths === 4) text = "per term";

              let priceDetail = priceDetails.find(
                (priceDetail) => priceDetail.currency === currency
              );
              if (priceDetail) {
                const { subscriptionPricePerMonth, subscriptionOneTimeFee } =
                  priceDetail;

                amount = Math.ceil(subscriptionPricePerMonth * termInMonths);

                if (subscriptionOneTimeFee !== 0) {
                  amount += subscriptionOneTimeFee;

                  if (termInMonths === 12) text = "for First year";
                  else if (termInMonths === 4) text = "for First quarter";

                  text2 = `${getFormattedCurrencyWithoutDecimals(
                    currency,
                    amount - subscriptionOneTimeFee
                  )} from 2nd ${
                    termInMonths === 12 ? "year" : "quarter"
                  } onwards`;
                }
              }

              return {
                amount,
                text,
                text2,
              };
            });

          if (
            productCategory === "RETAIL_PARENT" ||
            productCategory === "TUTION_EDUCATOR"
          ) {
            newConfig[productCategory][plan].classList = classes.map(
              ({ code, name }) => {
                return { text: name, value: code };
              }
            );
          }
        });
      }
    );
    setConfig(newConfig);
  }, [planPriceDetails, classes]);

  return (
    <>
      <div>
        <ContentWrapper>
          <Header theme="LIGHT" color={"white"} />
        </ContentWrapper>
      </div>
      <section className={style.out_box}>
        <div className={style.shape_box}>
          <div className={style.image_box}>
            <div className={style.box}>
              <span>AKADMY PRODUCTS</span>
              <h2>Subscription plans according to your needs.</h2>
              <Tab tab={tab} tabList={tabList} setTab={setTab} />
            </div>
          </div>
        </div>
      </section>
      <ContentWrapper>
        <section className={style.section2}>
          {/* <ProductCardHorizontal
            props={{ ...config[tab.productCategory].INTERAKTO }}
            handleAddToCart={handleAddToCart}
          /> */}
          <div className={style.card_container}>
            <ProductCard
              props={{ ...config[tab.productCategory].INTERAKTO }}
              handleAddToCart={handleAddToCart}
            />
            <ProductCard
              props={{ ...config[tab.productCategory].INTERAKTO_CODING }}
              handleAddToCart={handleAddToCart}
            />
            <ProductCard
              props={{ ...config[tab.productCategory].TEENYBEANS }}
              handleAddToCart={handleAddToCart}
            />
            <ProductCard
              props={{ ...config[tab.productCategory].TODDLERS }}
              handleAddToCart={handleAddToCart}
              classDisabled={true}
            />
          </div>
        </section>
      </ContentWrapper>
      <br />
      <br />
      <FAQ
        color1="#0348a8"
        color2={"#a0ace5"}
        color3="black"
        data={faqsPricing}
      />
      <Footer page="AKADEM_PRICING" />
    </>
  );
}

export default ProductPricingPage;
