import ContentWrapper from "../ContentWrapper/ContentWrapper";
import FAQ from "../FAQ/FAQ";
import Footer from "../Footer/Footer";
import Header from "../Header/Header";

import { useEffect, useState } from "react";
import style from "./PlatformPricingPage.module.css";

import DoneIcon from "@mui/icons-material/Done";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import { faqsPricing } from "../data/faqs";
import { createPurchase, getAkademyPlans, updatePurchase } from "../redux/purchaseSlice";
import PlatformCard from "./components/PlatformCard/PlatformCard";
import Tab from "./components/Tab/Tab";
import { educatorPlatformProducts, schoolPlatformProducts } from "./config";
import { useMediaQuery } from "@mui/material";
import { store } from "../redux/store";
import { Provider } from "react-redux";
const tabList = [
  { id: 1, text: "SCHOOLS", productCategory: "ENTERPRISE_SCHOOL" },
  { id: 2, text: "EDUCATORS", productCategory: "TUTION_EDUCATOR" },
];

const featureList = [
  {
    title: "Observations",
    desccription: "Easily track and note observations for each student.",
    uno: true,
    pro: "",
  },
  {
    title: "Observations With AI Assist",
    desccription:
      "Track observations with the help of AI to provide deeper insights.",
    uno: "",
    pro: true,
  },
  {
    title: "Simple Attendance",
    desccription: "Basic attendance tracking functionality.",
    uno: true,
    pro: "",
  },
  {
    title: "AI Powered Attendance Tracking",
    desccription:
      "Utilize facial recognition and other AI tools for more efficient attendance tracking.",
    uno: "",
    pro: true,
  },
  {
    title: "Posts for Class Updates",
    desccription: "Communicate class updates and announcements.",
    uno: true,
    pro: "",
  },
  {
    title: "Posts for Community Engagement",
    desccription: "Create posts that engage the entire school community.",
    uno: "",
    pro: true,
  },
  {
    title: "Simple Classroom Setup and Management",
    desccription: "Efficiently set up and manage classrooms.",
    uno: true,
    pro: "",
  },
  {
    title: "Classroom Management",
    desccription:
      "Comprehensive tools for managing classroom activities and resources.",
    uno: "",
    pro: true,
  },
  {
    title: "Progress Reports",
    desccription: "Generate and view progress reports for students.",
    uno: true,
    pro: "",
  },
  {
    title: "AI Powered Assessments Module",
    desccription:
      "Use AI to create and manage assessments tailored to student needs",
    uno: "",
    pro: true,
  },
  {
    title: "Storage",
    desccription: "For documents and multimedia.",
    uno: "Upto 1 GB",
    pro: "Upto 1 GB",
  },
  {
    title: "Communications & Messaging",
    desccription:
      "Advanced communication tools to stay in touch with parents and staff.",
    uno: "",
    pro: true,
  },
  {
    title: "Worksheets Creator Including AI Powered Magic Worksheets",
    desccription:
      "Create custom worksheets with AI assistance to enhance learning.",
    uno: "",
    pro: true,
  },
  {
    title: "Advanced Teacher Tools - Buzzboard Brainstorm",
    desccription: "Collaborate and brainstorm with advanced teacher tools.",
    uno: "",
    pro: true,
  },
];

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

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

  const [tab, setTab] = useState(tabList[0]);
  const [config, setConfig] = useState({
    TUTION_EDUCATOR: educatorPlatformProducts,
    ENTERPRISE_SCHOOL: schoolPlatformProducts,
  });

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

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

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

          newConfig[productCategory][plan].currency = currency;
          newConfig[productCategory][plan].planId = planDetails._id;
          newConfig[productCategory][plan].priceList = planDetails.variants.map(
            ({ termInMonths, priceDetails }) => {
              let text = "per seat / per month";
              let amount =
                priceDetails
                  .find((priceDetail) => priceDetail.currency === currency)
                  .licensePricePerMonth.find(
                    ({ licenseQuotaType }) => licenseQuotaType === "GENERAL"
                  ).pricePerMonth || 0;

              return {
                amount,
                text,
              };
            }
          );
        });
      }
    );
    setConfig(newConfig);
  }, [planPriceDetails]);

  const handleAddToCart = (props) => {
    const payload = {
      currency,
      cartItem: { planId: props.planId, planVariantIdx: props.priceIdx },
    };

    payload.cartItem.additionalLicenses = [
      {
        licenseQuotaType: "GENERAL",
        count: 1,
      },
    ];

    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);
      });
  };

  return (
    <>
      <Provider store={store}>
      <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 PLATFORM ACCESS</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}>
          <div className={style.card_container}>
            <PlatformCard
              props={{ ...config[tab.productCategory].UNO_PLATFORM }}
              handleAddToCart={handleAddToCart}
            />
            <PlatformCard
              props={{ ...config[tab.productCategory].PRO_PLATFORM }}
              handleAddToCart={handleAddToCart}
            />
          </div>
        </section>
      </ContentWrapper>
      <ContentWrapper>
        <section className={style.section3}>
          <h2 className={style.title}>Plans and Features</h2>

          <table
            cellPadding={useMediaQuery("(max-width:600px)") ? 6 : 20}
            className={style.feature_list}
          >
            <tr>
              <td>Features</td>
              <td>Uno</td>
              <td>Pro</td>
            </tr>
            {featureList.map(({ title, desccription, uno, pro }) => (
              <tr>
                <td>
                  <p>{title}</p>
                  <p>{desccription}</p>
                </td>
                <td>{uno === true ? <DoneIcon /> : uno}</td>
                <td>{pro === true ? <DoneIcon /> : pro}</td>
              </tr>
            ))}
          </table>
        </section>
      </ContentWrapper>

      <FAQ
        color1="#0348a8"
        color2={"#a0ace5"}
        color3="black"
        data={faqsPricing}
      />
      <Footer page="AKADEM_PRICING" />
      </Provider>
    </>
  );
}

export default PlatformPricingPage;
