import { useState,useEffect } from 'react';
import { Text,Banner, Page, Card, Button,BlockStack,InlineStack,CalloutCard} from '@shopify/polaris';
import styles from '../styles/app.plan.module.css';
import support from "./assets/support.jpg";
import {useLoaderData} from "@remix-run/react";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";
import { json } from "@remix-run/node";

export const loader = async ({ request }) => {
  const {session} = await authenticate.admin(request);

  console.log(session);

  const user = await prisma.users.findFirst({
    where:{
      shopurl:session.shop
    }
  });
  console.log(user);

  return json({user});
};

function Plan() {
 const {user} = useLoaderData();

 const [planType, setPlanType] = useState('Yearly');
 const [activePlan, setActivePlan] = useState(0);
 const [planId, setPlanId] = useState('0');

const planIdMapping = {
  0: "FREE-Monthly",
  1: "BRONZE-Monthly",
  2: "SILVER-Monthly",
  3: "GOLD-Monthly",
  4: "BRONZE-Yearly",
  5: "SILVER-Yearly",
  6: "GOLD-Yearly",
};

  useEffect(() => {
    async function fetchPlan() {
      const res = await fetch("/api/plan");
      const data = await res.json();

       const userPlanId = data.plan;
       setActivePlan(userPlanId);

      if ([4, 5, 6].includes(userPlanId)) {
       setPlanType("Yearly");
      } else {
       setPlanType("Monthly");
      }
    }
    fetchPlan();
  }, []);

  const handleTabChange = () => {
    setPlanType((prevType) => (prevType === 'Monthly' ? 'Yearly' : 'Monthly'));
  };

  const handleActivatePlan = async (planId) => {
    let url = "";
      if (planType === "Yearly" ) {
      url = `https://shopify.infoshore.biz/xpert/upgradeannual.php?key=${user.id}&type=${planId}`;
    } else {
      url = `https://shopify.infoshore.biz/xpert/upgrade2.php?key=${user.id}&type=${planId}`;
    }
    // window.location.href = url;
        window.open(url, "_top");



  // await fetch("/api/plan", {
  //   method: "POST",
  //   body: JSON.stringify({ plan: planId, userId: user?.id }),
  //   headers: { "Content-Type": "application/json" },
  // });
   setActivePlan(planId);

   console.log("plan : ", planId);
  };

  function renderPrice(
    original,
    discountedMonthly,
    discountedYearly,
    planType,
    userPlan,
  ) {
    if (userPlan !== 0) {
      return <span style={{ fontWeight: "bold" }}>{original}</span>;
    }

    const isYearly = planType === "Yearly";
    const discounted = isYearly ? discountedYearly : discountedMonthly;
    const percent = isYearly ? "32%" : "15%";

    return (
      <>
        <span style={{ textDecoration: "line-through", color: "gray" }}>
          {original}
        </span>{" "}
        <span style={{ fontWeight: "bold" }}>{discounted}</span>{" "}
        <span style={{ color: "green" }}>{percent} OFF</span>
      </>
    );
  }

  const getPlans = (planType) => [
    {
      id: 0,
      name: "FREE",
      price: "$0",
      period: "Valid for 30 days",
      features:
        planType === "Yearly"
          ? ["Manage 25 SKUs"]
          : ["Manage 25 SKUs"],
      notIncluded: [
        "Inventory Sync",
        "Price Sync",
        "Real-time Sync",
        "Priority Customer Support",
      ],
    },
    {
      id: planType === "Yearly" ? 4 : 1,
      name: "BRONZE",
      price: planType === "Yearly" ? "$199/year" : "$20/month",
      // price: renderPrice(
      //   planType === "Yearly" ? "$239.88/year" : "$19.99/mo",
      //   "$16.99/mo", // discounted monthly
      //   "$163.11/year", // discounted yearly
      //   planType,
      //   user.plan,
      // ),
      period: planType === "Monthly" ? "Billed at $199 per year" : "",
      features:
        planType === "Yearly"
          ? [
              "Manage 500 SKUs",
              "Inventory Sync",
              "Price Sync",
            ]
          : [
              "Manage 500 SKUsh",
              "Inventory Sync",
              "Price Sync",
            ],
      notIncluded: ["Real-time Sync", "Priority Customer Support"],
    },
    {
      id: planType === "Yearly" ? 5 : 2,
      name: "SILVER",
      price: planType === "Yearly" ? "$299/year" : "$30/month",
      // price: renderPrice(
      //   planType === "Yearly" ? "$360/year" : "$30/month", // original price
      //   "$25.50/month", // 15% discount monthly
      //   "$244.80/year", // 32% discount yearly
      //   planType,
      //   user.plan,
      // ),
      period: planType === "Monthly" ? "Billed at $299 per year" : "",
      features:
        planType === "Yearly"
          ? [
              "Manage 2000 SKUs",
              "Sync up to 6000 items",
              "Inventory Sync",
              "Price Sync",
              "Real-time Sync",
              "Priority Customer Support",
            ]
          : [
              "Manage 2000 SKUs",
              "Inventory Sync",
              "Price Sync",
              "Real-time Sync",
              "Priority Customer Support",
            ],
    },
    {
      id: planType === "Yearly" ? 6 : 3,
      name: "GOLD",
      price: planType === "Yearly" ? "$599/year" : "$60/month",
      // price: renderPrice(
      //   planType === "Yearly" ? "$720/year" : "$60/month", // original price
      //   "$51/month", // 15% discounted monthly price
      //   "$489.60/year", // 32% discounted yearly price
      //   planType,
      //   user.plan,
      // ),
      period: planType === "Monthly" ? "Billed at $599 per year" : "",
      features:
        planType === "Yearly"
          ? [
              "Manage 5000 SKUs",
              "Sync up to 15000 items",
              "Inventory Sync",
              "Price Sync",
              "Real-time Sync",
              "Priority Customer Support",
            ]
          : [
              "Manage 5000 SKUs",
              "Inventory Sync",
              "Price Sync",
              "Real-time Sync",
              "Priority Customer Support",
            ],
    },
  ];

 const plans = getPlans(planType);

  return (
    <Page
    fullWidth
    >
      {/* {user.plan == 0 && (
              <div style={{ marginBottom: "20px" }}>
                <>
                  <Banner
                    title={
                      <>
                        <>
                          <span style={{ fontSize: "30px" }}>🧑‍🎄</span> Christmas
                          Special: 15% OFF monthly | 32% OFF yearly!
                        </>
                      </>
                    }
                  ></Banner>
                </>
              </div>
            )} */}
      <div className={styles.title}>
        <Text variant="headingLg" as="h5">
          {planType} Plans With Real time Inventory Sync
        </Text>
      </div>

      <div className={styles.toggleSwitch}>
         <input
             type="checkbox"
             checked={planType === 'Yearly'}
             onChange={handleTabChange}
             id="plan-toggle"
             className={styles.checkbox}
         />
         <span>Billed Annually</span>
         <label htmlFor="plan-toggle" className={`${styles.switchLabel} ${
            planType === 'Monthly' ? styles.green : styles.gray
          }`}>
             <span
             className={`${styles.switchCircle} ${
             planType === 'Monthly' ? styles.switchRight : styles.switchLeft
             }`}
             ></span>
         </label>
         <span>Billed Monthly</span>
      </div>

      <div className={styles.planCards}>
        {plans.map((plan) => (
         <div key={plan.name} className={styles.planCardWrapper}> 
          <Card key={plan.name}>
           <div className={styles.cardContent}>
            <div className={`${styles.cardHeader} ${plan.name === "GOLD" ? styles.gold : styles.normal}`}>
              <Text variant="headingLg" as="h5">
                {plan.name} {planType === "Yearly" && plan.name !== "FREE" ? "Annual" : ''}
              </Text>
              <Text variant="headingMd" as="h5" tone="success">
                {plan.price}
              </Text>
              <Text tone='success'>{plan.period}</Text>
            </div>

            <div className={styles.cardBody}>
              {plan.features.map((f) => (
                <p key={f}>✓ {f}</p>
              ))}
              {plan.notIncluded &&
                plan.notIncluded.map((f) => <p key={f}>✗ {f}</p>)}
            </div>
            
            <div className={styles.activateButton}>
             <Button fullWidth
             variant={activePlan === plan.id ? "" : "primary"}
             disabled={activePlan === plan.id}
             onClick={() => handleActivatePlan(plan.id)}>
               {activePlan ===  plan.id ? "Activated" : "Activate Now"}
             </Button>
            </div>
           </div> 
          </Card>
         </div> 
        ))}
      </div>

      {/* <Card>
       <BlockStack gap="500" inlineAlign="center">
          <Text variant="headingMd" as="h6">Need More Than 5,000 SKUs?</Text>
          <Text>Yes we do support more than 5,000 amazon SKUs. Drop us an email at 
         <a href="mailto:shopifyapps@infoshore.biz" target="_blank">shopifyapps@infoshore.biz </a>for a quote with all the details.</Text>
        </BlockStack>
      </Card> */}
       <div style={{marginTop:"20px",}}>
          <InlineStack fullWidth>
            <CalloutCard
              title="Need More Than 5,000 SKUs?"
              fullWidth
              illustration={support}
              primaryAction={{
                content: "Email Now",
                url: "mailto:shopifyapps@infoshore.biz",
                // target: "_blank",
              }}>
              <Text as="p">
                Yes we do support more than 5,000 amazon SKUs. Drop us an email at {" "}
                <a href="mailto:shopifyapps@infoshore.biz" target="_blank">shopifyapps@infoshore.biz </a>
                for a quote with all the details.
              </Text>
            </CalloutCard>
          </InlineStack>
        </div>

        <p style={{ textAlign:"center", marginTop: "30px",color:"#666" }}>
          Copyright 2022 InfoShore Technology Solutions LLP. All rights reserved.
        </p>
    </Page>
  );
}
export default Plan;
