"use client";

import { useState } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import {
  Sparkles,
  Headphones,
  Award,
  Book,
  Check,
  Zap,
} from "lucide-react";

/* ------------------------------------------------------------------ */
/*  Pla n s                                                           */
/* ------------------------------------------------------------------ */

interface Plan {
  id: "app-learn-pass" | "app-learn-pass-annual";
  label: string;
  price: string;
  period: string;
  annual?: boolean;
  badge?: string;
}

const PLANS: Plan[] = [
  {
    id: "app-learn-pass",
    label: "Monthly",
    price: "$9.99",
    period: "/month",
    annual: false,
  },
  {
    id: "app-learn-pass-annual",
    label: "Annual",
    price: "$79.99",
    period: "/year",
    annual: true,
    badge: "2 months free",
  },
];

const FEATURES = [
  "Unlimited course access",
  "Audio lessons",
  "Certificates of completion",
  "Progress tracking",
  "New courses added regularly",
];

/* ------------------------------------------------------------------ */
/*  Comp o n e n t                                                     */
/* ------------------------------------------------------------------ */

export default function LearnPassCard() {
  const { user } = useAuth();
  const router = useRouter();
  const [selected, setSelected] = useState<"app-learn-pass" | "app-learn-pass-annual">(
    "app-learn-pass-annual"
  );
  const [paymentMethod, setPaymentMethod] = useState<"flh" | "card">("flh");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const activePlan = PLANS.find((p) => p.id === selected)!;
  const savingsNote =
    activePlan.annual
      ? `Save $39.89/year vs monthly`
      : null;

  const handleSubscribe = async () => {
    if (!user?.email) {
      setError("Please log in first");
      return;
    }
    setLoading(true);
    setError("");

    try {
      const res = await fetch("/mobile/api/learn/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          app_id: selected,
          customer_email: user.email,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Checkout failed");
      }

      if (data.checkout_url) {
        router.push(data.checkout_url);
      } else if (data.mock) {
        // Mock mode — redirect back to learn page
        router.push("/mobile/learn");
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  const handleFlhPurchase = async () => {
    if (!user?.email) {
      setError("Please log in first");
      return;
    }
    setLoading(true);
    setError("");

    try {
      const res = await fetch("/mobile/api/learn/pass/purchase", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          app_id: selected,
          customer_email: user.email,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Purchase failed");
      }

      // Successful FLH purchase — redirect to learn page
      router.push("/mobile/learn");
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  if (user?.isPremium) {
    return (
      <div className="mt-8 mx-0">
        <div className="bg-gradient-to-br from-emerald-900/20 to-[#111118] border border-emerald-800/30 rounded-2xl p-5 relative overflow-hidden">
          <div className="absolute -top-10 -right-10 w-32 h-32 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
          <div className="relative z-10 flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-emerald-900/40 flex items-center justify-center">
              <Zap size={20} className="text-emerald-400" />
            </div>
            <div>
              <p className="text-sm font-semibold text-white">
                Learn Pass Active
              </p>
              <p className="text-[11px] text-emerald-400/80">
                You have unlimited access to all courses
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="mt-8 mx-0">
      <div className="bg-gradient-to-br from-[#C9A84C]/10 to-[#C9A84C]/5 border border-[#C9A84C]/20 rounded-2xl p-5 relative overflow-hidden">
        {/* Decorative glow */}
        <div className="absolute -top-10 -right-10 w-32 h-32 bg-[#C9A84C]/10 rounded-full blur-3xl pointer-events-none" />
        <div className="absolute -bottom-8 -left-8 w-28 h-28 bg-[#00C48C]/5 rounded-full blur-3xl pointer-events-none" />

        <div className="relative z-10">
          {/* Header */}
          <div className="flex items-center gap-2 mb-1">
            <Sparkles size={18} className="text-[#C9A84C]" />
            <h3 className="text-base font-bold text-white">Learn Pass</h3>
          </div>
          <p className="text-xs text-gray-400 mb-5 leading-relaxed">
            Unlimited access to all courses, audio lessons, and certificates.
          </p>

          {/* Toggle: Monthly / Annual */}
          <div className="flex bg-[#0a0a0f] border border-gray-800/60 rounded-xl p-1 mb-5">
            {PLANS.map((plan) => (
              <button
                key={plan.id}
                onClick={() => setSelected(plan.id)}
                className={`flex-1 relative py-2.5 rounded-lg text-sm font-medium transition-all min-h-[44px] ${
                  selected === plan.id
                    ? "bg-[#C9A84C] text-[#07090C] shadow-md"
                    : "text-gray-400 hover:text-white"
                }`}
              >
                {plan.label}
                {plan.badge && (
                  <span
                    className={`absolute -top-2 right-1/2 translate-x-1/2 text-[9px] font-bold px-1.5 py-0.5 rounded-full whitespace-nowrap ${
                      selected === plan.id
                        ? "bg-[#07090C] text-[#C9A84C]"
                        : "bg-[#C9A84C]/20 text-[#C9A84C]"
                    }`}
                  >
                    {plan.badge}
                  </span>
                )}
              </button>
            ))}
          </div>

          {/* Pricing */}
          <div className="text-center mb-4">
            <span className="text-3xl font-bold text-white">
              {activePlan.price}
            </span>
            <span className="text-sm text-gray-500 ml-1">
              {activePlan.period}
            </span>
            {savingsNote && (
              <p className="text-[11px] text-emerald-400/80 mt-1">
                {savingsNote}
              </p>
            )}
          </div>

          {/* Features */}
          <ul className="space-y-2 mb-5">
            {FEATURES.map((f) => (
              <li key={f} className="flex items-center gap-2 text-xs text-gray-300">
                <Check size={14} className="text-[#C9A84C] shrink-0" />
                {f}
              </li>
            ))}
          </ul>

          {/* Payment method toggle */}
          <div className="flex bg-[#0a0a0f] border border-gray-800/60 rounded-xl p-1 mb-4">
            <button
              onClick={() => setPaymentMethod("flh")}
              className={`flex-1 py-2.5 rounded-lg text-xs font-medium transition-all min-h-[40px] ${
                paymentMethod === "flh"
                  ? "bg-[#00C48C] text-[#07090C] shadow-md"
                  : "text-gray-400 hover:text-white"
              }`}
            >
              Pay with FLH
            </button>
            <button
              onClick={() => setPaymentMethod("card")}
              className={`flex-1 py-2.5 rounded-lg text-xs font-medium transition-all min-h-[40px] ${
                paymentMethod === "card"
                  ? "bg-[#C9A84C] text-[#07090C] shadow-md"
                  : "text-gray-400 hover:text-white"
              }`}
            >
              Pay with Card
            </button>
          </div>

          {/* Action button */}
          {paymentMethod === "flh" ? (
            <button
              onClick={handleFlhPurchase}
              disabled={loading}
              className="w-full inline-flex items-center justify-center gap-2 bg-[#00C48C] text-[#07090C] text-sm font-semibold px-5 py-3 rounded-xl hover:bg-[#00C48C]/90 active:scale-[0.97] transition disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px]"
            >
              {loading ? (
                <span className="w-5 h-5 border-2 border-[#07090C]/30 border-t-[#07090C] animate-spin rounded-full" />
              ) : (
                <>
                  <Sparkles size={16} />
                  Pay with FLH — {activePlan.price}{activePlan.period}
                </>
              )}
            </button>
          ) : (
            <button
              onClick={handleSubscribe}
              disabled={loading}
              className="w-full inline-flex items-center justify-center gap-2 bg-[#C9A84C] text-[#07090C] text-sm font-semibold px-5 py-3 rounded-xl hover:bg-[#C9A84C]/90 active:scale-[0.97] transition disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px]"
            >
              {loading ? (
                <span className="w-5 h-5 border-2 border-[#07090C]/30 border-t-[#07090C] animate-spin rounded-full" />
              ) : (
                <>
                  <Sparkles size={16} />
                  Subscribe — {activePlan.price}{activePlan.period}
                </>
              )}
            </button>
          )}

          {/* Error */}
          {error && (
            <p className="mt-3 text-xs text-red-400 text-center">{error}</p>
          )}
        </div>
      </div>
    </div>
  );
}
