import React, { useState } from "react";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import MkdSDK from "Utils/MkdSDK";
import { InteractiveButton } from "Components/InteractiveButton";
import { LazyLoad } from "Components/LazyLoad";

/**
 * Creates a subscription plan in Stripe
 * @param {MkdSDK} sdk - SDK instance
 * @param {string} name - Plan name
 * @param {string} description - Plan description
 * @returns {Promise<{error: boolean, data?: any, message?: string}>}
 */
const createProduct = async (sdk, name, description) => {
  try {
    const result = await sdk.addStripeProduct({
      name,
      description,
    });
    return { error: false, data: result };
  } catch (error) {
    return { error: true, message: error.message };
  }
};

/**
 * Creates a price for a product in Stripe
 * @param {MkdSDK} sdk - SDK instance
 * @param {Object} priceData - Price data
 * @returns {Promise<{error: boolean, data?: any, message?: string}>}
 */
const createPrice = async (sdk, priceData) => {
  try {
    const result = await sdk.addStripePrice(priceData);
    return { error: false, data: result };
  } catch (error) {
    return { error: true, message: error.message };
  }
};

const SetupSubscriptionPlansPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [isLoading, setIsLoading] = useState(false);
  const [logs, setLogs] = useState([]);

  const addLog = (message, type = "info") => {
    setLogs((prev) => [
      ...prev,
      { message, type, timestamp: new Date().toISOString() },
    ]);
  };

  const setupSubscriptionPlans = async () => {
    const sdk = new MkdSDK();
    setIsLoading(true);
    addLog("Starting subscription plans setup...");

    const plans = [
      {
        name: "The Portal",
        description:
          "Complete project management solution for cheerleading music production",
        features: [
          "Project Management",
          "Project Calendar",
          "Client Login Portal",
          "Digital 8-count sheets",
          "Automated Music Licenses",
          "Automated Reminder Emails",
          "Automated Music Surveys",
          "Project Edit Management",
          "8-Count Track Management",
          "Custom Email Domain",
        ],
        productId: 2,
      },
      {
        name: "The Studio",
        description:
          "Advanced studio management features for cheerleading music production",
        features: [
          "Automated Music Surveys",
          "Project Management",
          "Project Calendar",
          "Project Budget Review",
          "Automated Vocal Orders",
          "Excel Style Order View",
          "Automated Reminder Emails",
          "Company Logo Customization",
          "Custom Email Domain",
        ],
        productId: 3,
      },
      {
        name: "Complete Suite",
        description:
          "All-inclusive solution with premium support for cheerleading music production",
        features: [
          "Everything in The Portal",
          "Everything in The Studio",
          "Priority Support",
          "Dedicated Account Manager",
        ],
        productId: 4,
      },
    ];

    const projectRanges = {
      "1-50": {
        portal: { monthly: 150, annual: 1500 },
        studio: { monthly: 150, annual: 1500 },
        complete: { monthly: 250, annual: 2500 },
      },
      "51-100": {
        portal: { monthly: 175, annual: 1750 },
        studio: { monthly: 175, annual: 1750 },
        complete: { monthly: 275, annual: 2750 },
      },
      "101-150": {
        portal: { monthly: 200, annual: 2000 },
        studio: { monthly: 200, annual: 2000 },
        complete: { monthly: 300, annual: 3000 },
      },
      "151-200": {
        portal: { monthly: 225, annual: 2250 },
        studio: { monthly: 225, annual: 2250 },
        complete: { monthly: 325, annual: 3250 },
      },
      "201+": {
        portal: { monthly: 250, annual: 2500 },
        studio: { monthly: 250, annual: 2500 },
        complete: { monthly: 350, annual: 3500 },
      },
    };

    const planKeys = {
      "The Portal": "portal",
      "The Studio": "studio",
      "Complete Suite": "complete",
    };

    try {
      // Create pricing tiers for all products
      for (const plan of plans) {
        const productId = plan.productId;
        const planKey = planKeys[plan.name];

        addLog(
          `Creating pricing tiers for ${plan.name} (Product ID: ${productId})`
        );

        // Create pricing tiers for each project range
        for (const [range, prices] of Object.entries(projectRanges)) {
          // Create monthly price
          const monthlyPrice = {
            product_id: productId,
            name: `${plan.name} - ${range} Projects - Monthly`,
            amount: prices[planKey].monthly,
            type: "recurring",
            interval: "month",
            interval_count: 1,
            usage_type: "licenced",
            trial_days: "0",
          };

          addLog(`Creating monthly price for ${plan.name} - ${range}`);
          const monthlyResult = await createPrice(sdk, monthlyPrice);
          if (monthlyResult.error) {
            addLog(
              `Failed to create monthly price for ${plan.name} ${range}: ${monthlyResult.message}`,
              "error"
            );
          } else {
            addLog(
              `Successfully created monthly price for ${plan.name} - ${range}`
            );
          }

          // Create annual price
          const annualPrice = {
            product_id: productId,
            name: `${plan.name} - ${range} Projects - Annual`,
            amount: prices[planKey].annual,
            type: "recurring",
            interval: "year",
            interval_count: 1,
            usage_type: "licenced",
            trial_days: "0",
          };

          addLog(`Creating annual price for ${plan.name} - ${range}`);
          const annualResult = await createPrice(sdk, annualPrice);
          if (annualResult.error) {
            addLog(
              `Failed to create annual price for ${plan.name} ${range}: ${annualResult.message}`,
              "error"
            );
          } else {
            addLog(
              `Successfully created annual price for ${plan.name} - ${range}`
            );
          }
        }
      }

      showToast(
        globalDispatch,
        "Successfully set up all pricing tiers",
        5000,
        "success"
      );
    } catch (error) {
      addLog(`Error during setup: ${error.message}`, "error");
      showToast(globalDispatch, error.message, 5000, "error");
      tokenExpireError(dispatch, error.message);
    } finally {
      setIsLoading(false);
      addLog("Setup process completed");
    }
  };

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

  return (
    <div className="bg-brown-main-bg mx-auto h-full p-5 shadow-md">
      <div className="mx-auto max-w-4xl">
        <h1 className="mb-6 text-2xl font-bold text-white">
          Setup Subscription Plans Pricing
        </h1>

        <div className="mb-6">
          <p className="mb-4 text-bodydark">
            This will create pricing tiers for all existing subscription plans
            in Stripe. This process will:
          </p>
          <ul className="mb-4 list-inside list-disc space-y-2 text-bodydark">
            <li>
              Set up pricing tiers for all plans:
              <ul className="ml-6 list-inside list-disc">
                <li>The Portal (ID: 2)</li>
                <li>The Studio (ID: 3)</li>
                <li>Complete Suite (ID: 4)</li>
              </ul>
            </li>
            <li>Create pricing for all project ranges (1-50, 51-100, etc.)</li>
            <li>Create both monthly and annual pricing options</li>
          </ul>
          <p className="mb-4 text-bodydark">
            Please make sure you haven't already set up these pricing tiers to
            avoid duplicates.
          </p>
        </div>

        <div className="mb-6">
          <LazyLoad>
            <InteractiveButton
              onClick={setupSubscriptionPlans}
              loading={isLoading}
              disabled={isLoading}
              color="white"
              className="w-full md:w-auto"
            >
              {isLoading ? "Setting up pricing..." : "Create Pricing Tiers"}
            </InteractiveButton>
          </LazyLoad>
        </div>

        {logs.length > 0 && (
          <div className="mt-8">
            <h2 className="mb-4 text-xl font-semibold text-white">
              Setup Logs
            </h2>
            <div className="max-h-96 overflow-y-auto rounded-lg bg-boxdark p-4">
              {logs.map((log, index) => (
                <div
                  key={index}
                  className={`mb-2 font-mono text-sm ${
                    log.type === "error" ? "text-red-400" : "text-bodydark"
                  }`}
                >
                  <span className="text-gray-500">
                    [{new Date(log.timestamp).toLocaleTimeString()}]
                  </span>{" "}
                  {log.message}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SetupSubscriptionPlansPage;
