"use client";

import { useState, useTransition } from "react";
import { CheckCircle, Sparkles, Briefcase, AlertCircle, Loader2 } from "lucide-react";

type Plan = {
  id: string;
  name: string;
  slug: string;
  description: string;
  priceUsd: number;
  priceNgn: number;
  module: string;
  features: string[];
  hasUsdLive: boolean;
  hasUsdSandbox: boolean;
  hasNgnLive: boolean;
  hasNgnSandbox: boolean;
  isOwned: boolean;
};

export default function SubscribePage({
  packages,
  requiredModule,
}: {
  packages: Plan[];
  requiredModule?: string;
  userModules: string[];
}) {
  const [currency, setCurrency] = useState<"usd" | "ngn">("usd");
  const [isPending, startTransition] = useTransition();
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function handleSubscribe(packageId: string) {
    setLoadingId(packageId);
    setError(null);
    startTransition(async () => {
      try {
        const res = await fetch("/api/checkout", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ packageId, currency }),
        });
        const data = await res.json();
        if (!res.ok) {
          setError(data.error ?? "Could not start checkout.");
          setLoadingId(null);
          return;
        }
        window.location.href = data.url;
      } catch {
        setError("Something went wrong. Please try again.");
        setLoadingId(null);
      }
    });
  }

  const icons: Record<string, React.ReactNode> = {
    academician: <Sparkles size={22} />,
    job_seeker: <Briefcase size={22} />,
  };

  const colors: Record<string, string> = {
    academician: "from-blue-600 to-indigo-700",
    job_seeker: "from-navy-700 to-navy-900",
  };

  return (
    <div className="min-h-screen bg-neutral-50">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 py-14">
        {/* Header */}
        <div className="text-center mb-10">
          <h1 className="text-3xl font-bold text-navy-800 mb-3">Choose Your Plan</h1>
          <p className="text-neutral-500 max-w-xl mx-auto">
            Unlock the modules you need. Subscribe to one or both plans — they work independently.
          </p>

          {requiredModule && (
            <div className="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-amber-50 border border-amber-200 text-amber-800 rounded-xl text-sm">
              <AlertCircle size={15} />
              You need a subscription to access this content.
            </div>
          )}
        </div>

        {/* Currency toggle */}
        <div className="flex justify-center mb-10">
          <div className="inline-flex bg-white border border-neutral-200 rounded-xl p-1">
            {(["usd", "ngn"] as const).map((c) => (
              <button
                key={c}
                onClick={() => setCurrency(c)}
                className={`px-5 py-2 rounded-lg text-sm font-semibold transition-all ${
                  currency === c
                    ? "bg-navy-700 text-white shadow-sm"
                    : "text-neutral-500 hover:text-navy-700"
                }`}
              >
                {c === "usd" ? "🇺🇸 USD" : "🇳🇬 NGN"}
              </button>
            ))}
          </div>
        </div>

        {/* Error */}
        {error && (
          <div className="max-w-lg mx-auto mb-6 p-4 bg-red-50 border border-red-200 text-red-700 rounded-xl text-sm flex items-start gap-2">
            <AlertCircle size={16} className="shrink-0 mt-0.5" />
            {error}
          </div>
        )}

        {/* Plan cards */}
        <div className="grid md:grid-cols-2 gap-6 max-w-3xl mx-auto">
          {packages.map((pkg) => {
            const priceId =
              currency === "usd"
                ? pkg.hasUsdSandbox || pkg.hasUsdLive
                : pkg.hasNgnSandbox || pkg.hasNgnLive;
            const priceReady = priceId;
            const isLoading = isPending && loadingId === pkg.id;
            const isHighlighted = requiredModule === pkg.module;

            return (
              <div
                key={pkg.id}
                className={`bg-white rounded-2xl border-2 overflow-hidden transition-all ${
                  isHighlighted ? "border-gold-400 shadow-lg" : "border-neutral-200"
                }`}
              >
                {/* Card header */}
                <div className={`bg-gradient-to-br ${colors[pkg.module] ?? "from-navy-700 to-navy-900"} p-6 text-white`}>
                  <div className="flex items-center gap-3 mb-4">
                    <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                      {icons[pkg.module] ?? <Sparkles size={20} />}
                    </div>
                    <div>
                      <div className="font-bold text-lg">{pkg.name}</div>
                      <div className="text-white/70 text-xs">Monthly · Cancel anytime</div>
                    </div>
                  </div>
                  <div className="text-3xl font-bold">
                    {currency === "usd"
                      ? `$${pkg.priceUsd.toFixed(0)}`
                      : `₦${pkg.priceNgn.toLocaleString()}`}
                    <span className="text-base font-normal text-white/70"> /mo</span>
                  </div>
                </div>

                {/* Features */}
                <div className="p-6">
                  <p className="text-neutral-500 text-sm mb-5">{pkg.description}</p>
                  <ul className="space-y-2.5 mb-6">
                    {pkg.features.map((f, i) => (
                      <li key={i} className="flex items-start gap-2.5 text-sm text-neutral-700">
                        <CheckCircle size={16} className="text-emerald-500 shrink-0 mt-0.5" />
                        {f}
                      </li>
                    ))}
                  </ul>

                  {pkg.isOwned ? (
                    <div className="w-full py-3 bg-emerald-50 text-emerald-700 font-semibold text-sm rounded-xl text-center flex items-center justify-center gap-2">
                      <CheckCircle size={16} /> Active Subscription
                    </div>
                  ) : !priceReady ? (
                    <div className="w-full py-3 bg-neutral-100 text-neutral-400 font-medium text-sm rounded-xl text-center">
                      Coming soon
                    </div>
                  ) : (
                    <button
                      onClick={() => handleSubscribe(pkg.id)}
                      disabled={isLoading}
                      className="w-full py-3 bg-navy-700 hover:bg-navy-800 text-white font-semibold text-sm rounded-xl transition-colors disabled:opacity-60 flex items-center justify-center gap-2"
                    >
                      {isLoading ? (
                        <>
                          <Loader2 size={16} className="animate-spin" /> Redirecting…
                        </>
                      ) : (
                        `Subscribe in ${currency.toUpperCase()}`
                      )}
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        <p className="text-center text-xs text-neutral-400 mt-8">
          Payments are securely processed by Stripe. You can cancel anytime from your dashboard.
        </p>
      </div>
    </div>
  );
}
