"use client";

import React, { useEffect, useState } from "react";
import axios from "axios";
import { useRouter } from "next/navigation";

interface Plan {
  name: string;
  desc: string;
  amountMonthly: number;
  amountYearly: number;
  features: string[];
  planId: string;
  yearlyPlanId: string;
  popular?: boolean;
}

interface CheckoutSessionResponse {
  url: string;
}

const StripePlans: React.FC = () => {
  const [loadingPlanId, setLoadingPlanId] = useState<string | null>(null);
  const [billingCycle, setBillingCycle] = useState<"monthly" | "yearly">("monthly");
  const [userId, setUserId] = useState<string | null>(null);
  const [user, setUser] = useState<string | null>(null);
  const router = useRouter();

  // 🧠 Check localStorage-based UID (manual login)
  useEffect(() => {
    const uid = localStorage.getItem("data4auto_uid");
    const userEmail = localStorage.getItem("d4a_email");

    if (uid && userEmail) {
      setUserId(uid);
      setUser(userEmail);
    } else {
      // ✅ If no uid in localStorage, check Google cookie
      axios
        .get("https://ebay.backend.data4autos.com/api/auth/protected", {
          withCredentials: true,
        })
        .then((res: any) => {
          setUser(res.data.user?.email);
          setUserId(res.data.user.userid);
          localStorage.setItem("data4auto_uid", res.data.user.userid);
        })
        .catch(() => {
          router.push("/login");
        });
    }
  }, [router]);

  const handleBuyNow = async (plan: Plan) => {
    try {
      setLoadingPlanId(plan.planId);

      const selectedPlanId =
        billingCycle === "yearly" ? plan.yearlyPlanId : plan.planId;

      const response = await axios.post<CheckoutSessionResponse>(
        "https://ebay.backend.data4autos.com/api/payment/create-checkout-session",
        { email: user, planId: selectedPlanId }
      );

      const { url } = response.data;
      if (!url) throw new Error("No checkout URL returned from backend");

      window.location.href = url;
    } catch (err: any) {
      console.error("Error creating checkout session:", err);
      alert(
        "Checkout failed: " +
          (err?.response?.data?.error || err?.message || "Unknown error")
      );
    } finally {
      setLoadingPlanId(null);
    }
  };

  const plans: Plan[] = [
    {
      name: "Starter Sync",
      desc: "Upload up to 100 products per month",
      amountMonthly: 49,
      amountYearly: 499,
      features: [
        "Auto price & inventory updates",
        "Daily sync",
        "Manual sync option",
        "Basic reporting dashboard",
      ],
      planId: "starter_monthly",
      yearlyPlanId: "starter_yearly",
    },
    {
      name: "Growth Sync",
      desc: "Upload up to 250 products per month",
      amountMonthly: 99,
      amountYearly: 999,
      features: [
        "Everything in Starter",
        "3-hour sync interval",
        "Bulk product import",
        "Priority email support",
      ],
      planId: "growth_monthly",
      yearlyPlanId: "growth_yearly",
      popular: true,
    },
    {
      name: "Pro Sync",
      desc: "Upload up to 1000 products per month",
      amountMonthly: 249,
      amountYearly: 2499,
      features: [
        "Everything in Growth",
        "Real-time sync",
        "Advanced analytics dashboard",
        "Dedicated account manager",
        "API access",
      ],
      planId: "pro_monthly",
      yearlyPlanId: "pro_yearly",
    },
  ];

  return (
    <div className="min-h-[83vh] bg-gradient-to-br from-[#00d1ff]/10 via-white to-[#00d1ff]/20 text-[#212529] py-16 px-4">
      <div className="max-w-6xl mx-auto text-center">
        {/* Header */}
        <h2 className="text-4xl font-extrabold mb-4 text-[#00d1ff]">
          Choose Your Plan
        </h2>
        <p className="text-gray-600 mb-10 max-w-2xl mx-auto">
          Subscribe to a plan and start automating your eBay listings instantly.
        </p>

        {/* Billing Cycle Toggle */}
        <div className="flex justify-center mb-12">
          <div className="bg-white border border-[#00d1ff] rounded-full p-1 flex">
            <button
              className={`px-6 py-2 rounded-full text-sm font-medium ${
                billingCycle === "monthly"
                  ? "bg-[#00d1ff] text-white"
                  : "text-[#00d1ff]"
              }`}
              onClick={() => setBillingCycle("monthly")}
            >
              Monthly
            </button>
            <button
              className={`px-6 py-2 rounded-full text-sm font-medium ${
                billingCycle === "yearly"
                  ? "bg-[#00d1ff] text-white"
                  : "text-[#00d1ff]"
              }`}
              onClick={() => setBillingCycle("yearly")}
            >
              Yearly (Save 15%)
            </button>
          </div>
        </div>

        {/* Plans */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
          {plans.map((plan) => (
            <div
              key={plan.name}
              className={`relative bg-white border border-[#00d1ff]/40 rounded-2xl shadow-lg hover:shadow-[0_0_20px_#00d1ff80] transition-all duration-300 p-8 flex flex-col ${
                plan.popular ? "ring-2 ring-[#00d1ff]" : ""
              }`}
            >
              {/* Badge */}
              {plan.popular && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-[#00d1ff] text-white text-xs font-bold px-3 py-1 rounded-full shadow-md">
                  MOST POPULAR
                </div>
              )}

              {/* Title */}
              <h3 className="text-2xl font-semibold mb-2">{plan.name}</h3>
              <p className="text-gray-700 text-sm mb-6">{plan.desc}</p>

              {/* Price */}
              <div className="text-center mb-6">
                <span
                  className={`text-4xl font-extrabold ${
                    plan.popular ? "text-[#00d1ff]" : "text-[#212529]"
                  }`}
                >
                  $
                  {billingCycle === "monthly"
                    ? plan.amountMonthly
                    : plan.amountYearly}
                </span>
                <span className="text-gray-500 text-sm">
                  {billingCycle === "monthly" ? " / month" : " / year"}
                </span>
              </div>

              {/* Features */}
              <ul className="space-y-2 text-gray-600 text-sm flex-1">
                {plan.features.map((feature, i) => (
                  <li key={i} className="flex items-center gap-2">
                    <span className="text-[#00d1ff]">✔</span> {feature}
                  </li>
                ))}
              </ul>

              {/* Button */}
              <button
                onClick={() => handleBuyNow(plan)}
                disabled={loadingPlanId === plan.planId}
                className={`mt-8 ${
                  plan.popular
                    ? "bg-[#00d1ff] text-[#212529] hover:bg-[#00b5e3]"
                    : "border border-[#00d1ff] text-[#00d1ff] hover:bg-[#00d1ff] hover:text-[#212529]"
                } font-medium py-3 rounded-lg shadow-md transition-all duration-200 disabled:opacity-50`}
              >
                {loadingPlanId === plan.planId
                  ? "Processing..."
                  : `Subscribe ${billingCycle === "yearly" ? "Yearly" : "Monthly"}`}
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default StripePlans;
