"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { loadStripe } from "@stripe/stripe-js";
import { Elements, CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import { Lock, ChevronLeft, ShoppingBag, Package, Loader2, CheckCircle, LogIn } from "lucide-react";

type CartItem = {
  productId: string;
  slug: string;
  name: string;
  price: number;
  quantity: number;
  image: string;
  variationId?: string;
};

// Load Stripe publishable key from meta tag set by layout
export default function CheckoutClient({ 
  stripePk, 
  savedShipping 
}: { 
  stripePk: string;
  savedShipping: {
    address: string;
    city: string;
    state: string;
    zip: string;
    country: string;
  } | null;
}) {
  const [items, setItems] = useState<CartItem[]>([]);
  const [mounted, setMounted] = useState(false);
  const [stripePromise, setStripePromise] = useState<ReturnType<typeof loadStripe> | null>(null);
  const { data: session, status } = useSession();
  const router = useRouter();

  useEffect(() => {
    setMounted(true);
    const raw = localStorage.getItem("kc_cart");
    if (raw) setItems(JSON.parse(raw));
    
    if (stripePk) {
      console.log("Loading Stripe with key:", stripePk.substring(0, 15) + "...");
      setStripePromise(loadStripe(stripePk));
    } else {
      console.error("No Stripe publishable key found");
    }
  }, [stripePk]);

  if (!mounted) return null;

  const total = items.reduce((s, i) => s + i.price * i.quantity, 0);

  // Show login prompt if not authenticated
  if (status === "loading") {
    return (
      <div className="min-h-screen bg-neutral-50 flex items-center justify-center">
        <div className="text-center">
          <Loader2 size={32} className="mx-auto mb-3 text-neutral-300 animate-spin" />
          <p className="text-neutral-400">Loading...</p>
        </div>
      </div>
    );
  }

  if (!session?.user) {
    return (
      <div className="min-h-screen bg-neutral-50 flex items-center justify-center">
        <div className="max-w-md mx-auto px-4">
          <div className="bg-white rounded-2xl border border-neutral-200 p-8 text-center shadow-sm">
            <div className="w-16 h-16 bg-navy-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <Lock size={28} className="text-navy-600" />
            </div>
            <h2 className="text-xl font-bold text-navy-900 mb-2">Sign in to Continue</h2>
            <p className="text-neutral-600 text-sm mb-6">You need to be logged in to complete your purchase.</p>
            <Link 
              href={`/login?callbackUrl=${encodeURIComponent("/shop/checkout")}`}
              className="flex items-center justify-center gap-2 w-full py-3 bg-navy-700 text-white font-semibold rounded-xl hover:bg-navy-800 transition-colors mb-3"
            >
              <LogIn size={16} /> Sign In
            </Link>
            <Link 
              href={`/register?callbackUrl=${encodeURIComponent("/shop/checkout")}`}
              className="block text-sm text-navy-600 hover:underline"
            >
              Don't have an account? Register
            </Link>
            <Link 
              href="/cart"
              className="block mt-4 text-sm text-neutral-400 hover:text-neutral-600"
            >
              ← Back to Cart
            </Link>
          </div>
        </div>
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="min-h-screen bg-neutral-50 flex items-center justify-center">
        <div className="text-center">
          <ShoppingBag size={56} className="mx-auto mb-4 text-neutral-200" />
          <h2 className="text-xl font-bold text-neutral-700 mb-3">Your cart is empty</h2>
          <Link href="/shop" className="px-6 py-3 bg-navy-700 text-white rounded-xl font-semibold hover:bg-navy-800">Browse Shop</Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-neutral-50">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div className="flex items-center gap-3 mb-8">
          <Link href="/cart" className="flex items-center gap-1 text-sm text-neutral-400 hover:text-navy-600">
            <ChevronLeft size={15} /> Back to Cart
          </Link>
        </div>
        <h1 className="text-2xl font-bold text-navy-900 mb-8 flex items-center gap-3">
          <Lock size={20} /> Secure Checkout
        </h1>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* Form */}
          <div className="lg:col-span-2">
            {!stripePk ? (
              <div className="bg-red-50 border border-red-200 rounded-2xl p-8 text-center">
                <p className="text-red-700 font-semibold mb-2">⚠️ Payment System Not Configured</p>
                <p className="text-red-600 text-sm">Stripe keys are not set up. Please contact the administrator.</p>
              </div>
            ) : stripePromise ? (
              <Elements stripe={stripePromise} options={{ locale: "en" }}>
                <CheckoutForm items={items} total={total} user={session.user} savedShipping={savedShipping} />
              </Elements>
            ) : (
              <div className="bg-white rounded-2xl border border-neutral-200 p-8 text-center">
                <Loader2 size={32} className="mx-auto mb-3 text-neutral-300 animate-spin" />
                <p className="text-neutral-400">Loading payment form...</p>
              </div>
            )}
          </div>

          {/* Order summary */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-2xl border border-neutral-200 p-6 sticky top-24">
              <h2 className="font-bold text-neutral-800 mb-4">Order Summary</h2>
              <div className="space-y-3 mb-4">
                {items.map(item => (
                  <div key={item.productId + (item.variationId ?? "")} className="flex items-start gap-3 text-sm">
                    <div className="w-10 h-10 rounded-lg bg-neutral-100 shrink-0 overflow-hidden">
                      {item.image ? (
                        <img src={item.image} alt={item.name} className="w-full h-full object-cover" />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-neutral-300"><Package size={16} /></div>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-neutral-800 line-clamp-2">{item.name}</div>
                      <div className="text-neutral-400 text-xs">Qty: {item.quantity}</div>
                    </div>
                    <div className="font-semibold text-navy-700 shrink-0">${(item.price * item.quantity).toFixed(2)}</div>
                  </div>
                ))}
              </div>
              <div className="border-t border-neutral-200 pt-4">
                <div className="flex justify-between font-bold text-lg">
                  <span>Total</span>
                  <span className="text-navy-700">${total.toFixed(2)}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function CheckoutForm({ 
  items, 
  total, 
  user,
  savedShipping 
}: { 
  items: CartItem[]; 
  total: number; 
  user: { name?: string | null; email?: string | null; id?: string };
  savedShipping: {
    address: string;
    city: string;
    state: string;
    zip: string;
    country: string;
  } | null;
}) {
  const stripe = useStripe();
  const elements = useElements();
  const router = useRouter();

  const [step, setStep] = useState<"form" | "paying" | "done">("form");
  const [error, setError] = useState("");
  const [form, setForm] = useState({
    name: user.name || "",
    email: user.email || "",
    phone: "",
    address: savedShipping?.address || "",
    city: savedShipping?.city || "",
    state: savedShipping?.state || "",
    zip: savedShipping?.zip || "",
    country: savedShipping?.country || "Malaysia",
  });

  function handleChange(e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    setForm(f => ({ ...f, [e.target.name]: e.target.value }));
  }

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

    try {
      // Create order + payment intent
      const res = await fetch("/api/shop/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          items,
          contact: { name: form.name, email: form.email, phone: form.phone },
          shipping: { address: form.address, city: form.city, state: form.state, zip: form.zip, country: form.country },
        }),
      });
      const data = await res.json() as { clientSecret?: string; orderId?: string; error?: string };

      if (!res.ok || !data.clientSecret) {
        setError(data.error ?? "Failed to create order. Please try again.");
        setStep("form");
        return;
      }

      // Confirm card payment
      const cardElement = elements.getElement(CardElement);
      if (!cardElement) { setStep("form"); return; }

      const { error: stripeError, paymentIntent } = await stripe.confirmCardPayment(data.clientSecret, {
        payment_method: {
          card: cardElement,
          billing_details: { name: form.name, email: form.email },
        },
      });

      if (stripeError) {
        setError(stripeError.message ?? "Payment failed. Please check your card details.");
        setStep("form");
        return;
      }

      if (paymentIntent?.status === "succeeded") {
        // Mark order as paid
        await fetch("/api/shop/checkout", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ orderId: data.orderId, paymentIntentId: paymentIntent.id }),
        });
        // Clear cart
        localStorage.removeItem("kc_cart");
        window.dispatchEvent(new Event("cart-updated"));
        setStep("done");
        setTimeout(() => router.push(`/shop/order-success?orderId=${data.orderId}`), 2000);
      }
    } catch {
      setError("An unexpected error occurred. Please try again.");
      setStep("form");
    }
  }

  if (step === "done") {
    return (
      <div className="bg-white rounded-2xl border border-emerald-200 p-12 text-center">
        <CheckCircle size={56} className="mx-auto mb-4 text-emerald-500" />
        <h2 className="text-2xl font-bold text-emerald-800 mb-2">Payment Successful!</h2>
        <p className="text-neutral-500 text-sm">Thank you for your order. You will receive a confirmation email shortly.</p>
        <p className="text-neutral-400 text-xs mt-3">Redirecting you back to the shop…</p>
      </div>
    );
  }

  const inp = "w-full border border-neutral-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-navy-500";
  const field = (label: string, name: keyof typeof form, type = "text", placeholder = "") => (
    <div>
      <label className="block text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-1.5">{label}</label>
      <input name={name} type={type} value={form[name]} onChange={handleChange} required className={inp} placeholder={placeholder} />
    </div>
  );

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Contact */}
      <div className="bg-white rounded-2xl border border-neutral-200 p-6">
        <h2 className="font-bold text-neutral-800 mb-4">Contact Information</h2>
        <div className="grid sm:grid-cols-2 gap-4">
          {field("Full Name", "name")}
          {field("Email Address", "email", "email")}
          {field("Phone (optional)", "phone", "tel")}
        </div>
      </div>

      {/* Shipping */}
      <div className="bg-white rounded-2xl border border-neutral-200 p-6">
        <h2 className="font-bold text-neutral-800 mb-4">Shipping Address</h2>
        <div className="grid gap-4">
          {field("Street Address", "address")}
          <div className="grid sm:grid-cols-2 gap-4">
            {field("City", "city")}
            {field("State", "state")}
          </div>
          <div className="grid sm:grid-cols-2 gap-4">
            {field("Postcode", "zip")}
            <div>
              <label className="block text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-1.5">Country</label>
              <select name="country" value={form.country} onChange={handleChange} className={inp + " bg-white"}>
                <option value="Malaysia">Malaysia</option>
                <option value="Singapore">Singapore</option>
                <option value="Indonesia">Indonesia</option>
                <option value="Other">Other</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* Payment */}
      <div className="bg-white rounded-2xl border border-neutral-200 p-6">
        <h2 className="font-bold text-neutral-800 mb-4 flex items-center gap-2">
          <Lock size={16} className="text-neutral-400" /> Payment Details
        </h2>
        <div className="border border-neutral-300 rounded-lg px-3 py-3">
          <CardElement options={{ style: { base: { fontSize: "14px", color: "#1a1a2e", "::placeholder": { color: "#9ca3af" } } } }} />
        </div>
        <p className="text-[11px] text-neutral-400 mt-2">Your card details are secured by Stripe. We never store card numbers.</p>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3 text-sm text-red-700">{error}</div>
      )}

      <button type="submit" disabled={step === "paying" || !stripe}
        className="w-full flex items-center justify-center gap-2 py-4 bg-navy-700 text-white font-bold text-base rounded-xl hover:bg-navy-800 disabled:opacity-60 transition-colors">
        {step === "paying" ? <><Loader2 size={18} className="animate-spin" /> Processing…</> : <>
          <Lock size={16} /> Pay ${total.toFixed(2)}
        </>}
      </button>
    </form>
  );
}
