import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import CustomSelect2 from "Components/CustomSelect2";
import { AuthContext } from "Src/authContext";
import { GlobalContext } from "Src/globalContext";
import MkdSDK from "Utils/MkdSDK";

const pricingRanges = {
  "1-50": {
    portal: { monthly: 200, annual: 2200 },
    studio: { monthly: 250, annual: 2500 },
    complete: { monthly: 350, annual: 3500 },
  },
  "51-100": {
    portal: { monthly: 300, annual: 3300 },
    studio: { monthly: 350, annual: 3600 },
    complete: { monthly: 450, annual: 4600 },
  },
  "101-150": {
    portal: { monthly: 400, annual: 4400 },
    studio: { monthly: 450, annual: 4700 },
    complete: { monthly: 550, annual: 5700 },
  },
  "151-200": {
    portal: { monthly: 500, annual: 5500 },
    studio: { monthly: 550, annual: 5800 },
    complete: { monthly: 650, annual: 6800 },
  },
  "201+": {
    portal: { monthly: 600, annual: 6600 },
    studio: { monthly: 650, annual: 6900 },
    complete: { monthly: 750, annual: 7900 },
  },
};

const PlansPage = () => {
  const { state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [selectedProjectRange, setSelectedProjectRange] = useState("1-50");
  const [billingCycle, setBillingCycle] = useState("monthly");
  const [loading, setLoading] = useState(false);
  const sdk = new MkdSDK();

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "plans",
      },
    });
  }, []);

  const handleSubscribe = async (plan) => {
    try {
      setLoading(true);

      // Get the price based on the selected plan and billing cycle
      const price =
        billingCycle === "monthly"
          ? pricingRanges[selectedProjectRange][plan].monthly
          : pricingRanges[selectedProjectRange][plan].annual;

      // Create checkout session
      const session = await sdk.initCheckoutSession({
        priceId: `${plan}_${billingCycle}_${selectedProjectRange}`,
        successUrl: `${window.location.origin}/member/dashboard?session_id={CHECKOUT_SESSION_ID}`,
        cancelUrl: `${window.location.origin}/member/plans`,
        customerId: authState.user?.stripeCustomerId,
        mode: "subscription",
        price: price,
        quantity: 1,
      });

      // Redirect to Stripe Checkout
      window.location.href = session.url;
    } catch (error) {
      console.error("Subscription error:", error);
      globalDispatch({
        type: "SHOW_TOAST",
        payload: {
          text:
            error.message ||
            "Failed to process subscription. Please try again.",
          type: "error",
        },
      });
    } finally {
      setLoading(false);
    }
  };

  // Calculate the monthly price for annual billing
  const getMonthlyPrice = (plan) => {
    const annualPrice = pricingRanges[selectedProjectRange][plan].annual;
    return Math.round(annualPrice / 12);
  };

  // Calculate savings percentage for annual billing
  const getSavings = (plan) => {
    const monthlyPrice = pricingRanges[selectedProjectRange][plan].monthly;
    const annualMonthlyPrice = getMonthlyPrice(plan);
    return Math.round(
      ((monthlyPrice - annualMonthlyPrice) / monthlyPrice) * 100
    );
  };

  return (
    <div className="p-4 mx-auto max-w-screen-2xl md:p-6 2xl:p-10">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-white">Subscription Plans</h2>
        <p className="mt-2 text-lg text-bodydark">
          Choose the right plan for your business
        </p>
      </div>

      <div className="flex gap-4 justify-between items-center mb-8 w-full">
        <div className="flex gap-4 items-center">
          <span className="font-medium text-white whitespace-nowrap">
            Show pricing for
          </span>
          <div className="w-[200px]">
            <CustomSelect2
              label="Show pricing for"
              value={selectedProjectRange}
              defaultValue={selectedProjectRange}
              onChange={(value) => setSelectedProjectRange(value)}
              className="px-4 py-2 text-white whitespace-nowrap bg-transparent rounded-lg border outline-none border-stroke focus:border-primary"
            >
              <option value="1-50">1-50 Mix Projects</option>
              <option value="51-100">51-100 Mix Projects</option>
              <option value="101-150">101-150 Mix Projects</option>
              <option value="151-200">151-200 Mix Projects</option>
              <option value="201+">201+ Mix Projects</option>
            </CustomSelect2>
          </div>
        </div>

        <div className="flex gap-3 items-center">
          <button
            onClick={() => setBillingCycle("monthly")}
            className={`rounded-lg px-4 py-2 ${
              billingCycle === "monthly"
                ? "bg-primary text-white"
                : "bg-boxdark text-bodydark"
            }`}
          >
            Monthly
          </button>
          <button
            onClick={() => setBillingCycle("annual")}
            className={`rounded-lg px-4 py-2 ${
              billingCycle === "annual"
                ? "bg-primary text-white"
                : "bg-boxdark text-bodydark"
            }`}
          >
            Annual
          </button>
        </div>
      </div>

      <div className="grid gap-8 md:grid-cols-3">
        {/* The Portal Plan */}
        <div className="p-8 rounded-xl bg-boxdark">
          <h3 className="mb-4 text-xl font-semibold text-white">The Portal</h3>
          <p className="mb-6 text-4xl font-bold text-primary">
            $
            {billingCycle === "monthly"
              ? pricingRanges[selectedProjectRange].portal.monthly
              : getMonthlyPrice("portal")}
            <span className="text-lg text-bodydark">/mo</span>
          </p>
          {billingCycle === "annual" && (
            <p className="mb-2 text-sm text-success-500">
              Save {getSavings("portal")}% with annual billing
            </p>
          )}
          <p className="mb-4 text-sm text-white">
            ${pricingRanges[selectedProjectRange].portal.annual} billed annually
          </p>
          <ul className="mb-8 space-y-4 text-bodydark">
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Project Management
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Project Calendar
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Client Login Portal
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Digital 8-count sheets
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Automated Music Licenses
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Automated Reminder Emails
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Automated Music Surveys
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Project Edit Management
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              8-Count Track Management
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Custom Email Domain
            </li>
          </ul>
          <button
            onClick={() => handleSubscribe("portal")}
            disabled={loading}
            className="px-8 py-3 w-full font-semibold bg-transparent rounded-full border transition-all border-primary text-primary hover:bg-primary/80 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
          >
            {loading ? "Processing..." : "Subscribe Now"}
          </button>
        </div>

        {/* The Studio Plan */}
        <div className="p-8 rounded-xl bg-boxdark">
          <h3 className="mb-4 text-xl font-semibold text-white">The Studio</h3>
          <p className="mb-6 text-4xl font-bold text-primary">
            $
            {billingCycle === "monthly"
              ? pricingRanges[selectedProjectRange].studio.monthly
              : getMonthlyPrice("studio")}
            <span className="text-lg text-bodydark">/mo</span>
          </p>
          {billingCycle === "annual" && (
            <p className="mb-2 text-sm text-success-500">
              Save {getSavings("studio")}% with annual billing
            </p>
          )}
          <p className="mb-4 text-sm text-white">
            ${pricingRanges[selectedProjectRange].studio.annual} billed annually
          </p>
          <ul className="mb-8 space-y-4 text-bodydark">
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Automated Music Surveys
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Project Management
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Project Calendar
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Project Budget Review
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Automated Vocal Orders
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Excel Style Order View
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Automated Reminder Emails
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Company Logo Customization
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Custom Email Domain
            </li>
          </ul>
          <button
            onClick={() => handleSubscribe("studio")}
            disabled={loading}
            className="px-8 py-3 w-full font-semibold text-white rounded-full transition-all bg-primary hover:bg-opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {loading ? "Processing..." : "Subscribe Now"}
          </button>
        </div>

        {/* Complete Suite Plan */}
        <div className="p-8 rounded-xl bg-boxdark">
          <h3 className="mb-4 text-xl font-semibold text-white">
            Complete Suite
          </h3>
          <p className="mb-6 text-4xl font-bold text-primary">
            $
            {billingCycle === "monthly"
              ? pricingRanges[selectedProjectRange].complete.monthly
              : getMonthlyPrice("complete")}
            <span className="text-lg text-bodydark">/mo</span>
          </p>
          {billingCycle === "annual" && (
            <p className="mb-2 text-sm text-success-500">
              Save {getSavings("complete")}% with annual billing
            </p>
          )}
          <p className="mb-4 text-sm text-white">
            ${pricingRanges[selectedProjectRange].complete.annual} billed
            annually
          </p>
          <ul className="mb-8 space-y-4 text-bodydark">
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Everything in The Portal
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Everything in The Studio
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Priority Support
            </li>
            <li className="flex gap-2 items-center">
              <FontAwesomeIcon
                icon="fa-solid fa-check"
                className="text-primary"
              />
              Dedicated Account Manager
            </li>
          </ul>
          <button
            onClick={() => handleSubscribe("complete")}
            disabled={loading}
            className="px-8 py-3 w-full font-semibold bg-transparent rounded-full border transition-all border-primary text-primary hover:bg-primary/80 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
          >
            {loading ? "Processing..." : "Subscribe Now"}
          </button>
        </div>
      </div>
    </div>
  );
};

export default PlansPage;
