"use client";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { loadStripe } from "@stripe/stripe-js";
import { Elements, CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import { Suspense } from "react";

const BRAND_LABELS: Record<string, string> = {
  visa: "Visa", mastercard: "Mastercard", amex: "Amex", discover: "Discover",
};
const BRAND_ICONS: Record<string, string> = {
  visa: "💳", mastercard: "💳", amex: "💳", discover: "💳",
};

function AddCardForm({ onSuccess }: { onSuccess: () => void }) {
  const stripe = useStripe();
  const elements = useElements();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!stripe || !elements) return;
    setSaving(true);
    setError("");

    const cardEl = elements.getElement(CardElement);
    if (!cardEl) return;

    const { error: stripeErr, setupIntent } = await stripe.confirmCardSetup(
      (elements as any)._commonOptions?.clientSecret || "",
      { payment_method: { card: cardEl } }
    );

    if (stripeErr) {
      setError(stripeErr.message || "Could not save card.");
      setSaving(false);
      return;
    }

    // Mark the newly confirmed payment method as the default
    if (setupIntent?.payment_method) {
      await fetch("/api/payment-methods/set-default", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ paymentMethodId: setupIntent.payment_method }),
      });
    }

    onSuccess();
    setSaving(false);
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
        <CardElement
          options={{
            style: {
              base: { color: "#f5f5f5", fontSize: "15px", "::placeholder": { color: "#6b7280" }, iconColor: "#f5f5f5" },
              invalid: { color: "#ef4444" },
            },
          }}
        />
      </div>
      {error && <p className="text-red-500 text-sm">{error}</p>}
      <button type="submit" disabled={saving || !stripe} className="btn-primary w-full py-3">
        {saving ? "Saving..." : "Save Card"}
      </button>
    </form>
  );
}

function PaymentMethodsInner() {
  const { status } = useSession();
  const router = useRouter();
  const [methods, setMethods] = useState<any[]>([]);
  const [defaultId, setDefaultId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [showAdd, setShowAdd] = useState(false);
  const [stripePromise, setStripePromise] = useState<any>(null);
  const [clientSecret, setClientSecret] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    if (status === "unauthenticated") router.push("/login");
  }, [status, router]);

  async function load() {
    setLoading(true);
    const res = await fetch("/api/payment-methods/list");
    const data = await res.json();
    setMethods(data.methods || []);
    setDefaultId(data.defaultId || null);
    setLoading(false);
  }

  useEffect(() => { load(); }, []);

  async function startAdd() {
    setError("");
    const res = await fetch("/api/payment-methods/setup", { method: "POST" });
    const data = await res.json();
    if (!res.ok) { setError(data.error); return; }
    const stripe = await loadStripe(data.publishableKey);
    setStripePromise(stripe);
    setClientSecret(data.clientSecret);
    setShowAdd(true);
  }

  async function setDefault(id: string) {
    await fetch("/api/payment-methods/set-default", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ paymentMethodId: id }),
    });
    load();
  }

  async function remove(id: string) {
    await fetch("/api/payment-methods/remove", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ paymentMethodId: id }),
    });
    load();
  }

  return (
    <div className="max-w-lg mx-auto">
      <h1 className="text-2xl font-bold mb-6">Payment Methods</h1>

      {loading ? (
        <p className="text-neutral-500 text-sm text-center py-10">Loading...</p>
      ) : (
        <div className="space-y-3 mb-6">
          {methods.length === 0 && !showAdd && (
            <div className="card p-8 text-center text-neutral-500 text-sm">No saved cards yet.</div>
          )}
          {methods.map((m) => {
            const card = m.card || {};
            const isDefault = m.id === defaultId;
            return (
              <div key={m.id} className={`card p-4 flex items-center gap-3 ${isDefault ? "border-red-600" : ""}`}>
                <span className="text-2xl">{BRAND_ICONS[card.brand] || "💳"}</span>
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-sm">
                    {BRAND_LABELS[card.brand] || card.brand} •••• {card.last4}
                    {isDefault && <span className="ml-2 text-xs text-red-500 font-semibold">Default</span>}
                  </p>
                  <p className="text-xs text-neutral-500">Expires {card.exp_month}/{card.exp_year}</p>
                </div>
                <div className="flex gap-2 shrink-0">
                  {!isDefault && (
                    <button onClick={() => setDefault(m.id)} className="text-xs text-neutral-400 hover:text-white">
                      Set default
                    </button>
                  )}
                  <button onClick={() => remove(m.id)} className="text-xs text-red-500 hover:text-red-400">
                    Remove
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {error && <p className="text-red-500 text-sm mb-3">{error}</p>}

      {showAdd && clientSecret && stripePromise ? (
        <div className="card p-5 mb-4">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold">Add New Card</h2>
            <button onClick={() => setShowAdd(false)} className="text-neutral-500 hover:text-white text-sm">Cancel</button>
          </div>
          <Elements stripe={stripePromise} options={{ clientSecret }}>
            <AddCardForm onSuccess={() => { setShowAdd(false); load(); }} />
          </Elements>
        </div>
      ) : (
        !loading && (
          <button onClick={startAdd} className="btn-primary w-full py-3">
            + Add New Card
          </button>
        )
      )}
    </div>
  );
}

export default function PaymentMethodsPage() {
  return (
    <Suspense fallback={<div className="text-center py-10 text-neutral-500 text-sm">Loading...</div>}>
      <PaymentMethodsInner />
    </Suspense>
  );
}
