"use client";
import { useEffect, useState } from "react";
import { loadStripe, Stripe } from "@stripe/stripe-js";
import { CheckoutElementsProvider, useCheckoutElements, PaymentElement, ShippingAddressElement } from "@stripe/react-stripe-js/checkout";
import { useRouter, useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";
import PaymentSuccessCard from "@/components/PaymentSuccessCard";

function PaymentForm({
  paymentId,
  amount,
  isSubscription,
  isTip,
  email,
  loggedIn,
  needsShipping,
}: {
  paymentId: string;
  amount: number;
  isSubscription: boolean;
  isTip: boolean;
  email: string;
  loggedIn: boolean;
  needsShipping: boolean;
}) {
  const result = useCheckoutElements();
  const [submitting, setSubmitting] = useState(false);
  const [termsAgreed, setTermsAgreed] = useState(false);
  const [showTermsAlert, setShowTermsAlert] = useState(false);
  const [error, setError] = useState("");
  const [succeeded, setSucceeded] = useState(false);
  const [addressValue, setAddressValue] = useState<{ name: string; address: any } | null>(null);
  const [addressComplete, setAddressComplete] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (result.type !== "success" || !result.checkout.canConfirm) return;
    if (!termsAgreed) {
      setShowTermsAlert(true);
      return;
    }
    setSubmitting(true);
    setError("");

    try {
      // Physical products collect a shipping address right here in the same
      // form — validated before we ever attempt to charge the card.
      let shipping: any = undefined;
      let checkoutShippingAddress: any = undefined;
      if (needsShipping) {
        if (!addressComplete || !addressValue) {
          setError("Please enter a complete shipping address.");
          return;
        }
        const a = addressValue.address;
        shipping = {
          name: addressValue.name,
          addressLine1: a.line1,
          addressLine2: a.line2 || undefined,
          city: a.city,
          state: a.state,
          postalCode: a.postal_code,
          country: a.country,
        };
        checkoutShippingAddress = { name: addressValue.name, address: a };
      }

      // Stripe only allows setting the return destination once — either at
      // session creation (server-side, already done in
      // /api/checkout/embedded) or here at confirm() time, never both.
      // Passing it here too was the exact cause of "You cannot provide
      // returnUrl to confirm()...", which was silently blocking every
      // single payment.
      const confirmResult = await result.checkout.confirm({
        redirect: "if_required",
        ...(checkoutShippingAddress ? { shippingAddress: checkoutShippingAddress } : {}),
      });

      if (confirmResult.type === "error") {
        setError(confirmResult.error.message || "Payment failed. Please check your card details and try again.");
        return;
      }

      if (confirmResult.session.status.type === "complete" && confirmResult.session.status.paymentStatus === "paid") {
        // Confirm with our own server right away instead of waiting on the
        // Stripe webhook, which can lag several seconds behind (or never
        // arrive if it's misconfigured) — this is what was making fresh
        // purchases look like they "didn't go through" in My Library.
        try {
          await fetch("/api/checkout/confirm", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ paymentId, shipping }),
          });
        } catch {}
        setSucceeded(true);
        return;
      }

      // Any other outcome (still processing, needs more action, an
      // unrecognized status) — surface something instead of silently
      // sitting on "Processing..." with no explanation.
      setError("This payment needs a bit more time or another step to complete. Please check your card details and try again.");
    } catch (err: any) {
      // A genuine thrown exception (network failure, an unexpected Stripe.js
      // error, anything not returned as a normal {type: "error"} result) —
      // this is exactly what was leaving the button stuck on "Processing..."
      // forever with no feedback at all.
      setError(err?.message || "Something went wrong completing the payment. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  if (succeeded) {
    return (
      <PaymentSuccessCard
        paymentId={paymentId}
        isSubscription={isSubscription}
        isTip={isTip}
        amount={amount}
        email={email}
        loggedIn={loggedIn}
      />
    );
  }

  if (result.type === "loading") {
    return <p className="text-neutral-500 text-sm text-center py-8">Loading checkout...</p>;
  }
  if (result.type === "error") {
    return <p className="text-red-500 text-sm text-center py-8">{result.error.message}</p>;
  }

  return (
    <form onSubmit={handleSubmit} className="card p-6 space-y-5">
      {showTermsAlert && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 px-4">
          <div className="bg-neutral-900 border border-neutral-700 rounded-2xl p-6 max-w-sm w-full shadow-2xl text-center">
            <div className="text-4xl mb-3">📋</div>
            <h3 className="font-bold text-lg mb-2">Please agree to our Terms</h3>
            <p className="text-sm text-neutral-400 mb-5">
              You must read and agree to our Terms &amp; Conditions before completing your payment.
            </p>
            <button
              type="button"
              onClick={() => setShowTermsAlert(false)}
              className="btn-primary w-full py-3"
            >
              Got it, I'll review them
            </button>
          </div>
        </div>
      )}
      {needsShipping && (
        <div>
          <p className="text-sm font-semibold mb-3">Shipping address</p>
          <ShippingAddressElement
            onChange={(e) => {
              setAddressComplete(e.complete);
              setAddressValue(e.value);
            }}
          />
        </div>
      )}
      <div>
        {needsShipping && <p className="text-sm font-semibold mb-3">Payment</p>}
        <p className="text-neutral-400 text-sm mb-4">Pay with card, Apple Pay, Google Pay, and more.</p>
        <PaymentElement
          options={{
            layout: "tabs",
            wallets: {
              applePay: "auto",
              googlePay: "auto",
              link: "auto",
            },
          }}
        />
      </div>
      {error && <p className="text-red-500 text-sm">{error}</p>}

      <label className="flex items-start gap-3 cursor-pointer group">
        <div
          onClick={() => setTermsAgreed(!termsAgreed)}
          className={`mt-0.5 w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors ${
            termsAgreed ? "bg-red-600 border-red-600" : "border-neutral-600 group-hover:border-red-500"
          }`}
        >
          {termsAgreed && <span className="text-white text-xs font-bold">✓</span>}
        </div>
        <span className="text-sm text-neutral-400 leading-snug">
          I have read and agree to the{" "}
          <a href="/terms" target="_blank" onClick={(e) => e.stopPropagation()} className="text-red-400 hover:text-red-300 underline">Terms &amp; Conditions</a>
          {" "}and{" "}
          <a href="/privacy" target="_blank" onClick={(e) => e.stopPropagation()} className="text-red-400 hover:text-red-300 underline">Privacy Policy</a>.
        </span>
      </label>

      <button
        type="submit"
        disabled={!result.checkout.canConfirm || submitting}
        className={`w-full py-3.5 rounded-xl font-bold text-base transition-all ${
          termsAgreed
            ? "bg-red-600 hover:bg-red-700 text-white"
            : "bg-neutral-800 text-neutral-500"
        }`}
      >
        {submitting ? "Processing..." : isTip ? `Give $${amount.toFixed(2)}` : isSubscription ? `Confirm upgrade — $${amount.toFixed(2)}` : `Complete purchase — $${amount.toFixed(2)}`}
      </button>
      <p className="text-center text-xs text-neutral-500">🔒 Secure payments via Stripe · Cancel anytime</p>
    </form>
  );
}

// Reads the payment details straight from the URL's search params, so any
// page can send someone here just by linking to the right query string —
// no server-rendered props needed. Handles:
//   ?tier=plus&amount=24.99&description=Plus+Membership&interval=month  (subscription)
//   ?type=purchase&amount=10&description=...&productId=abc              (one-time)
//   ?type=tip&amount=10&name=...&message=...&email=...&isRecurring=1    (tip — guest allowed)
export default function EmbeddedCheckoutClient() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const { data: session } = useSession();
  const [clientSecret, setClientSecret] = useState("");
  const [paymentId, setPaymentId] = useState("");
  const [needsShipping, setNeedsShipping] = useState(false);
  const [stripePromise, setStripePromise] = useState<Promise<Stripe | null> | null>(null);
  const [error, setError] = useState("");
  const [needsEmail, setNeedsEmail] = useState(false);
  const [emailInput, setEmailInput] = useState("");
  const [amount, setAmount] = useState(0);
  const [description, setDescription] = useState("");

  const tier = searchParams.get("tier") || "";
  const isTip = searchParams.get("type") === "tip";
  const isSubscription = !isTip && (!!tier || searchParams.get("type") === "subscription");
  const loggedIn = !!session?.user;
  const imageUrl = searchParams.get("imageUrl") || "";

  const subtitle = isTip
    ? searchParams.get("isRecurring") === "1"
      ? "Recurring monthly support"
      : "One-time gift"
    : isSubscription
    ? `Recurring membership · Billed ${searchParams.get("interval") || "month"}ly`
    : needsShipping
    ? "Physical item · Ships to you"
    : "Digital download · Instant access";

  function start(emailOverride?: string) {
    const amt = parseFloat(searchParams.get("amount") || "0");
    const desc = searchParams.get("description") || (isTip ? "Support the Creators" : isSubscription ? "Membership" : "Purchase");
    const interval = searchParams.get("interval") || "month";
    const type = searchParams.get("type") || (isSubscription ? "subscription" : "purchase");
    const productId = searchParams.get("productId") || "";
    setAmount(amt);
    setDescription(desc);
    setError("");
    setNeedsEmail(false);

    const email = emailOverride ?? emailInput ?? searchParams.get("email") ?? "";

    const body: Record<string, any> = { type: isSubscription ? "subscription" : type, amount: amt, description: desc, tier, interval, productId };
    if (isTip) {
      body.name = searchParams.get("name") || "Anonymous";
      body.message = searchParams.get("message") || "";
      body.email = email || undefined;
      body.isRecurring = searchParams.get("isRecurring") === "1";
      body.isPublic = searchParams.get("isPublic") !== "0";
    }

    fetch("/api/checkout/embedded", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    })
      .then(async (r) => {
        if (r.status === 401) {
          router.push(`/login?redirect=${encodeURIComponent(window.location.pathname + window.location.search)}`);
          return null;
        }
        return r.json();
      })
      .then((data) => {
        if (!data) return; // already redirecting to /login
        if (data.error) {
          if (isTip && /email/i.test(data.error)) {
            setNeedsEmail(true);
          } else {
            setError(data.error);
          }
          return;
        }
        setClientSecret(data.clientSecret);
        setPaymentId(data.paymentId);
        setNeedsShipping(!!data.needsShipping);
        setStripePromise(loadStripe(data.publishableKey));
      })
      .catch(() => setError("Could not start checkout. Please try again."));
  }

  useEffect(() => {
    start();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (needsEmail) {
    return (
      <div className="max-w-md mx-auto card p-6">
        <p className="text-sm mb-3">Recurring support needs an email on file, so we can send you receipts and let you manage it later.</p>
        <input
          type="email"
          value={emailInput}
          onChange={(e) => setEmailInput(e.target.value)}
          placeholder="you@example.com"
          className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600 mb-3"
        />
        <button onClick={() => start(emailInput)} disabled={!emailInput.trim()} className="btn-primary w-full py-3">
          Continue
        </button>
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-md mx-auto card p-6 text-center">
        <p className="text-red-500 mb-2">{error}</p>
        <a href={isTip ? "/tips" : isSubscription ? "/subscription/plans" : "/shop"} className="text-sm text-neutral-400 underline">
          ← Back to {isTip ? "tips" : isSubscription ? "plans" : "shop"}
        </a>
      </div>
    );
  }

  if (!clientSecret || !stripePromise) {
    return (
      <div className="max-w-md mx-auto text-center py-16">
        <p className="text-neutral-500 animate-pulse">Preparing secure checkout...</p>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto">
      <h1 className="text-xl font-bold mb-4 text-center">
        {isTip ? "Complete Your Gift" : isSubscription ? "Complete Your Upgrade" : "Complete Your Purchase"}
      </h1>

      <div className="card p-4 mb-4 flex items-center gap-3">
        {imageUrl ? (
          <img src={imageUrl} className="w-14 h-14 rounded-lg object-cover shrink-0" alt="" />
        ) : (
          <div className="w-14 h-14 rounded-lg bg-neutral-800 flex items-center justify-center text-2xl shrink-0">
            {isTip ? "🙏" : isSubscription ? "⭐" : "🛍"}
          </div>
        )}
        <div className="min-w-0 flex-1">
          <p className="font-semibold text-sm truncate">{description}</p>
          <p className="text-xs text-neutral-500">{subtitle}</p>
        </div>
        <p className="font-bold text-sm shrink-0">
          ${amount.toFixed(2)}
          {isSubscription && <span className="text-neutral-500 font-normal">/{searchParams.get("interval") || "mo"}</span>}
        </p>
      </div>

      <CheckoutElementsProvider stripe={stripePromise} options={{ clientSecret, elementsOptions: { appearance: { theme: "night" } } }}>
        <PaymentForm
          paymentId={paymentId}
          amount={amount}
          isSubscription={isSubscription}
          isTip={isTip}
          email={emailInput || searchParams.get("email") || ""}
          loggedIn={loggedIn}
          needsShipping={needsShipping}
        />
      </CheckoutElementsProvider>
    </div>
  );
}
