import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Lock, ArrowLeft, CreditCard, Zap, ShieldCheck, Landmark, Bitcoin, CheckCircle2 } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import SiteLayout from "@/components/SiteLayout";
import { useCart } from "@/context/CartContext";
import LoadingSpinner from "@/components/LoadingSpinner";
import { toast } from "sonner";
import { Price } from "@/components/ui/Price";

const client = createClient();

type PaymentMethod = "paypal" | "stripe" | "bank" | "crypto";

interface ShippingAddressForm {
  full_name: string;
  line1: string;
  line2: string;
  city: string;
  state: string;
  postal_code: string;
  country: string;
  phone: string;
}

const emptyAddress: ShippingAddressForm = {
  full_name: "",
  line1: "",
  line2: "",
  city: "",
  state: "",
  postal_code: "",
  country: "",
  phone: "",
};

interface PaymentOption {
  id: PaymentMethod;
  label: string;
  tagline: string;
  logoEl: React.ReactNode;
  disabled: boolean;
  badge?: string;
}

function PayPalLogo() {
  // Inline PayPal wordmark (blue + darker blue) — keeps us independent of external CDN
  return (
    <svg viewBox="0 0 124 33" className="h-7 w-auto" aria-label="PayPal">
      <path
        fill="#253B80"
        d="M46.2 6.8h-6.9c-.5 0-.9.3-1 .8l-2.8 17.7c-.1.4.2.7.6.7h3.3c.5 0 .9-.3 1-.8l.8-4.8c.1-.4.5-.8 1-.8h2.2c4.6 0 7.2-2.2 7.9-6.6.3-1.9 0-3.4-.9-4.4-1-1.2-2.9-1.8-5.2-1.8zm.8 6.5c-.4 2.5-2.3 2.5-4.1 2.5h-1l.7-4.6c0-.3.3-.5.6-.5h.5c1.2 0 2.4 0 3 .7.4.4.5 1 .3 1.9z"
      />
      <path
        fill="#253B80"
        d="M64.8 13.2h-3.3c-.3 0-.6.2-.6.5l-.1.9-.2-.3c-.7-1-2.2-1.4-3.7-1.4-3.5 0-6.4 2.6-7 6.3-.3 1.9.1 3.7 1.2 4.9 1 1.2 2.4 1.6 4.1 1.6 2.8 0 4.3-1.8 4.3-1.8l-.1.9c-.1.4.2.7.6.7h3c.5 0 .9-.3 1-.8l1.8-11.3c.1-.4-.2-.7-.6-.7zm-4.6 6.1c-.3 1.8-1.7 3-3.6 3-.9 0-1.7-.3-2.2-.9-.5-.6-.7-1.4-.5-2.3.3-1.8 1.7-3 3.5-3 .9 0 1.7.3 2.2.9.5.6.7 1.4.6 2.3z"
      />
      <path
        fill="#253B80"
        d="M82.5 13.2h-3.3c-.3 0-.6.2-.8.4l-4.6 6.7-1.9-6.5c-.1-.4-.5-.7-.9-.7h-3.2c-.4 0-.7.4-.6.8l3.6 10.6-3.4 4.8c-.3.4 0 .9.5.9h3.3c.3 0 .6-.1.8-.4l11-15.9c.2-.3 0-.7-.5-.7z"
      />
      <path
        fill="#179BD7"
        d="M93.3 6.8h-6.9c-.5 0-.9.3-1 .8l-2.8 17.7c-.1.4.2.7.6.7h3.6c.3 0 .6-.3.7-.6l.8-5c.1-.4.5-.8 1-.8h2.2c4.6 0 7.2-2.2 7.9-6.6.3-1.9 0-3.4-.9-4.4-1.1-1.2-2.9-1.8-5.2-1.8zm.8 6.5c-.4 2.5-2.3 2.5-4.1 2.5h-1l.7-4.6c0-.3.3-.5.6-.5h.5c1.2 0 2.4 0 3 .7.4.4.5 1 .3 1.9z"
      />
      <path
        fill="#179BD7"
        d="M111.9 13.2h-3.3c-.3 0-.6.2-.6.5l-.1.9-.2-.3c-.7-1-2.2-1.4-3.7-1.4-3.5 0-6.4 2.6-7 6.3-.3 1.9.1 3.7 1.2 4.9 1 1.2 2.4 1.6 4.1 1.6 2.8 0 4.3-1.8 4.3-1.8l-.1.9c-.1.4.2.7.6.7h3c.5 0 .9-.3 1-.8l1.8-11.3c.1-.4-.2-.7-.6-.7zm-4.6 6.1c-.3 1.8-1.7 3-3.6 3-.9 0-1.7-.3-2.2-.9-.5-.6-.7-1.4-.5-2.3.3-1.8 1.7-3 3.5-3 .9 0 1.7.3 2.2.9.5.6.6 1.4.6 2.3z"
      />
      <path
        fill="#179BD7"
        d="M115.8 7.3l-2.8 18.2c-.1.4.2.7.6.7h2.9c.5 0 .9-.3 1-.8l2.8-17.7c.1-.4-.2-.7-.6-.7h-3.3c-.3 0-.5.1-.6.3z"
      />
    </svg>
  );
}

function StripeLogo() {
  return (
    <div className="inline-flex items-center gap-2">
      <div className="bg-[#635BFF] rounded-md px-2 py-1 text-white font-extrabold text-xs tracking-tight">
        stripe
      </div>
      <CreditCard className="w-5 h-5 text-white/80" />
    </div>
  );
}

export default function Checkout() {
  const { lines, subtotal, hasPhysical, clearCart } = useCart();
  const navigate = useNavigate();

  const [authChecked, setAuthChecked] = useState(false);
  const [loggedIn, setLoggedIn] = useState(false);
  const [billingEmail, setBillingEmail] = useState("");
  const [address, setAddress] = useState<ShippingAddressForm>(emptyAddress);
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [method, setMethod] = useState<PaymentMethod>("paypal");
  const [paypalConfigured, setPaypalConfigured] = useState<boolean | null>(null);

  const shippingEstimate = hasPhysical ? (subtotal >= 75 ? 0 : 7.99) : 0;
  const total = subtotal + shippingEstimate;

  useEffect(() => {
    const run = async () => {
      try {
        const me = await client.auth.me();
        const u = me?.data;
        if (u) {
          setLoggedIn(true);
          const anyU = u as any;
          setBillingEmail(anyU.email || anyU.user_email || "");
        }
      } catch {
        setLoggedIn(false);
      } finally {
        setAuthChecked(true);
      }
    };
    const loadPaypal = async () => {
      try {
        const res = await client.apiCall.invoke({
          url: "/api/v1/paypal/config",
          method: "GET",
        });
        const data: any = res?.data;
        setPaypalConfigured(Boolean(data?.configured));
        if (data && data.configured === false) {
          setMethod("stripe");
        }
      } catch {
        setPaypalConfigured(false);
        setMethod("stripe");
      }
    };
    run();
    loadPaypal();
  }, []);

  const handleAddr =
    (key: keyof ShippingAddressForm) =>
    (e: React.ChangeEvent<HTMLInputElement>) =>
      setAddress((a) => ({ ...a, [key]: e.target.value }));

  const validate = (): string | null => {
    if (!billingEmail.trim()) return "Please enter a billing email.";
    if (lines.length === 0) return "Your cart is empty.";
    if (hasPhysical) {
      if (!address.full_name.trim()) return "Please enter full name.";
      if (!address.line1.trim()) return "Please enter address line 1.";
      if (!address.city.trim()) return "Please enter a city.";
      if (!address.postal_code.trim()) return "Please enter a postal code.";
      if (!address.country.trim()) return "Please enter a country.";
    }
    return null;
  };

  const handleCheckout = async () => {
    const err = validate();
    if (err) {
      toast.error(err);
      return;
    }
    if (!loggedIn) {
      toast.info("Please log in to complete checkout.");
      await client.auth.toLogin();
      return;
    }
    if (method === "bank" || method === "crypto") {
      toast.info("This payment method is coming soon. Please pick PayPal or Card for now.");
      return;
    }

    setSubmitting(true);
    try {
      const itemsPayload = lines.map((l) => ({
        product_id: l.product_id,
        quantity: l.quantity,
        variant_label: l.variant_label,
      }));

      if (method === "paypal") {
        const res = await client.apiCall.invoke({
          url: "/api/v1/paypal/create_order",
          method: "POST",
          data: {
            items: itemsPayload,
            return_url: "/shop/payment-success?provider=paypal",
            cancel_url: "/shop/checkout",
            billing_email: billingEmail,
            shipping_address: hasPhysical ? address : undefined,
            notes,
          },
        });
        const data: any = res?.data;
        if (!data?.approve_url) {
          toast.error("Unable to start PayPal checkout.");
          return;
        }
        clearCart();
        if (client.utils?.openUrl) {
          client.utils.openUrl(data.approve_url);
        } else {
          window.location.href = data.approve_url;
        }
      } else {
        // Stripe
        const res = await client.apiCall.invoke({
          url: "/api/v1/ecom/create_payment_session",
          method: "POST",
          data: {
            items: itemsPayload,
            success_url: "/shop/payment-success?provider=stripe&session_id={CHECKOUT_SESSION_ID}",
            cancel_url: "/shop/checkout",
            billing_email: billingEmail,
            shipping_address: hasPhysical ? address : undefined,
            notes,
          },
        });
        const data: any = res?.data;
        if (!data?.url) {
          toast.error("Unable to start payment session.");
          return;
        }
        clearCart();
        if (client.utils?.openUrl) {
          client.utils.openUrl(data.url);
        } else {
          window.location.href = data.url;
        }
      }
    } catch (e: any) {
      toast.error(e?.message || "Failed to create payment session.");
    } finally {
      setSubmitting(false);
    }
  };

  if (!authChecked) {
    return (
      <SiteLayout>
        <div className="py-24 flex justify-center">
          <LoadingSpinner />
        </div>
      </SiteLayout>
    );
  }

  if (lines.length === 0) {
    return (
      <SiteLayout>
        <div className="max-w-3xl mx-auto px-4 md:px-6 py-24 text-center">
          <h1 className="text-2xl font-bold text-slate-900">Your cart is empty</h1>
          <p className="text-slate-500 mt-2">
            Add items to your cart before continuing to checkout.
          </p>
          <Link
            to="/shop"
            className="mt-6 inline-flex items-center gap-2 text-[#0b6e3e] font-semibold"
          >
            <ArrowLeft className="w-4 h-4" /> Back to shop
          </Link>
        </div>
      </SiteLayout>
    );
  }

  const options: PaymentOption[] = [
    {
      id: "paypal",
      label: "PayPal",
      tagline: "Fast & secure · Instant activation after payment",
      logoEl: <PayPalLogo />,
      disabled: paypalConfigured === false,
      badge: "Recommended",
    },
    {
      id: "stripe",
      label: "Credit / Debit Card",
      tagline: "Visa · Mastercard · Amex — processed by Stripe",
      logoEl: <StripeLogo />,
      disabled: false,
    },
    {
      id: "bank",
      label: "Bank Transfer",
      tagline: "Manual wire transfer — coming soon",
      logoEl: <Landmark className="w-6 h-6 text-white/80" />,
      disabled: true,
      badge: "Soon",
    },
    {
      id: "crypto",
      label: "Crypto",
      tagline: "BTC / ETH / USDT — coming soon",
      logoEl: <Bitcoin className="w-6 h-6 text-white/80" />,
      disabled: true,
      badge: "Soon",
    },
  ];

  const ctaLabel =
    method === "paypal"
      ? "Continue to PayPal"
      : method === "stripe"
      ? "Pay securely with Card"
      : "Choose an available method";

  return (
    <SiteLayout>
      <div className="max-w-6xl mx-auto px-4 md:px-6 py-10">
        <Link
          to="/shop/cart"
          className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-[#0b6e3e] mb-4"
        >
          <ArrowLeft className="w-4 h-4" /> Back to cart
        </Link>
        <h1 className="text-3xl md:text-4xl font-extrabold text-slate-900 mb-6">
          Checkout
        </h1>

        <div className="grid lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-6">
            {/* Contact */}
            <div className="bg-white border border-slate-200 rounded-2xl p-6">
              <h2 className="font-bold text-slate-900 mb-3">Contact</h2>
              <input
                type="email"
                value={billingEmail}
                onChange={(e) => setBillingEmail(e.target.value)}
                placeholder="you@example.com"
                className="w-full border border-slate-200 rounded-lg px-3 py-2.5 text-sm"
              />
              {!loggedIn && (
                <p className="text-xs text-slate-500 mt-2">
                  You will be asked to log in to complete your purchase and access order history.
                </p>
              )}
            </div>

            {/* Shipping (physical only) */}
            {hasPhysical && (
              <div className="bg-white border border-slate-200 rounded-2xl p-6">
                <h2 className="font-bold text-slate-900 mb-3">Shipping address</h2>
                <div className="grid md:grid-cols-2 gap-3">
                  <input value={address.full_name} onChange={handleAddr("full_name")} placeholder="Full name" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm md:col-span-2" />
                  <input value={address.line1} onChange={handleAddr("line1")} placeholder="Address line 1" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm md:col-span-2" />
                  <input value={address.line2} onChange={handleAddr("line2")} placeholder="Address line 2 (optional)" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm md:col-span-2" />
                  <input value={address.city} onChange={handleAddr("city")} placeholder="City" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm" />
                  <input value={address.state} onChange={handleAddr("state")} placeholder="State / Region" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm" />
                  <input value={address.postal_code} onChange={handleAddr("postal_code")} placeholder="Postal code" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm" />
                  <input value={address.country} onChange={handleAddr("country")} placeholder="Country" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm" />
                  <input value={address.phone} onChange={handleAddr("phone")} placeholder="Phone (optional)" className="border border-slate-200 rounded-lg px-3 py-2.5 text-sm md:col-span-2" />
                </div>
              </div>
            )}

            {/* Payment Method — Dark Premium Selector */}
            <div className="rounded-2xl p-6 bg-gradient-to-br from-[#0a0f1c] via-[#0d1528] to-[#111b33] border border-white/10 shadow-2xl">
              <div className="flex items-center justify-between mb-4 flex-wrap gap-2">
                <h2 className="text-white font-extrabold text-lg tracking-tight">
                  Payment method
                </h2>
                <div className="inline-flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#f5c400] font-bold">
                  <ShieldCheck className="w-3.5 h-3.5" /> 256-bit encrypted
                </div>
              </div>

              <div className="grid sm:grid-cols-2 gap-3">
                {options.map((opt) => {
                  const active = method === opt.id;
                  const dim = opt.disabled;
                  return (
                    <button
                      key={opt.id}
                      type="button"
                      onClick={() => !dim && setMethod(opt.id)}
                      disabled={dim}
                      className={[
                        "group relative text-left rounded-xl p-4 transition-all duration-200 border",
                        dim
                          ? "opacity-50 cursor-not-allowed border-white/5 bg-white/[0.02]"
                          : active
                          ? "border-[#25d366] bg-gradient-to-br from-[#0b3a24] to-[#0a2e20] shadow-[0_0_0_3px_rgba(37,211,102,0.18),0_12px_30px_-10px_rgba(37,211,102,0.45)]"
                          : "border-white/10 bg-white/[0.03] hover:border-[#f5c400]/60 hover:bg-white/[0.06]",
                      ].join(" ")}
                    >
                      {opt.badge && (
                        <span
                          className={[
                            "absolute -top-2 right-3 text-[10px] font-bold px-2 py-0.5 rounded-full",
                            opt.id === "paypal"
                              ? "bg-[#f5c400] text-slate-900"
                              : "bg-white/10 text-white/70 border border-white/10",
                          ].join(" ")}
                        >
                          {opt.badge}
                        </span>
                      )}
                      <div className="flex items-center justify-between gap-3">
                        <div className="flex items-center gap-3">
                          <div className="bg-white/10 border border-white/10 rounded-lg px-2.5 py-1.5 min-w-[56px] flex items-center justify-center">
                            {opt.logoEl}
                          </div>
                          <div>
                            <div className="text-white font-bold">{opt.label}</div>
                            <div className="text-white/60 text-xs mt-0.5">{opt.tagline}</div>
                          </div>
                        </div>
                        <div
                          className={[
                            "w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0",
                            active
                              ? "border-[#25d366] bg-[#25d366]"
                              : "border-white/30",
                          ].join(" ")}
                        >
                          {active && <CheckCircle2 className="w-4 h-4 text-slate-900" />}
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>

              {method === "paypal" && (
                <div className="mt-4 rounded-xl bg-white/5 border border-[#f5c400]/30 p-3 flex items-start gap-3">
                  <Zap className="w-4 h-4 text-[#f5c400] mt-0.5 flex-shrink-0" />
                  <p className="text-xs text-white/80 leading-relaxed">
                    You'll be redirected to PayPal to complete your payment securely.
                    After approval, your service will be activated instantly and an
                    email confirmation will be sent.
                  </p>
                </div>
              )}
              {paypalConfigured === false && (
                <p className="mt-3 text-[11px] text-amber-300/80">
                  PayPal is temporarily unavailable. Please pay with Card.
                </p>
              )}
            </div>

            {/* Notes */}
            <div className="bg-white border border-slate-200 rounded-2xl p-6">
              <h2 className="font-bold text-slate-900 mb-3">Order notes (optional)</h2>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={3}
                placeholder="Add any special instructions…"
                className="w-full border border-slate-200 rounded-lg px-3 py-2.5 text-sm"
              />
            </div>
          </div>

          {/* Summary */}
          <aside className="bg-white border border-slate-200 rounded-2xl p-6 h-fit sticky top-6">
            <h2 className="font-bold text-slate-900 mb-3">Order summary</h2>
            <div className="space-y-3 max-h-64 overflow-y-auto pr-1">
              {lines.map((l) => (
                <div
                  key={`${l.product_id}-${l.variant_label}`}
                  className="flex gap-3 text-sm"
                >
                  <div className="w-14 h-14 rounded-lg bg-slate-50 overflow-hidden flex-shrink-0 relative">
                    {l.image_url ? (
                      <img
                        src={l.image_url}
                        alt={l.name}
                        className="w-full h-full object-cover"
                      />
                    ) : null}
                    <span className="absolute -top-1 -right-1 bg-[#0b6e3e] text-white text-[10px] font-bold rounded-full w-5 h-5 flex items-center justify-center">
                      {l.quantity}
                    </span>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-semibold text-slate-900 line-clamp-1">
                      {l.name}
                    </div>
                    {l.variant_label && (
                      <div className="text-xs text-slate-500">{l.variant_label}</div>
                    )}
                  </div>
                  <div className="font-semibold text-slate-900 whitespace-nowrap">
                    <Price amount={l.unit_price * l.quantity} />
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t border-slate-200 my-4" />
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-slate-600">Subtotal</span>
                <span className="font-semibold"><Price amount={subtotal} /></span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-600">Shipping</span>
                <span className="font-semibold">
                  {hasPhysical ? (
                    shippingEstimate === 0 ? (
                      "Free"
                    ) : (
                      <Price amount={shippingEstimate} />
                    )
                  ) : (
                    "—"
                  )}
                </span>
              </div>
              <div className="flex justify-between border-t border-slate-200 pt-2">
                <span className="font-bold text-slate-900">Total</span>
                <span className="text-xl font-extrabold text-[#0b6e3e]">
                  <Price amount={total} />
                </span>
              </div>
            </div>
            <button
              onClick={handleCheckout}
              disabled={submitting || method === "bank" || method === "crypto"}
              className={[
                "mt-5 w-full py-3 rounded-xl text-white font-bold inline-flex items-center justify-center gap-2 transition-all",
                method === "paypal"
                  ? "bg-gradient-to-r from-[#003087] to-[#009cde] hover:from-[#002569] hover:to-[#0087c0] shadow-lg shadow-blue-500/20"
                  : "bg-[#0b6e3e] hover:bg-[#0a8048]",
                "disabled:opacity-60 disabled:cursor-not-allowed",
              ].join(" ")}
            >
              {method === "paypal" ? (
                <Zap className="w-4 h-4" />
              ) : (
                <CreditCard className="w-4 h-4" />
              )}
              {submitting ? "Redirecting…" : ctaLabel}
            </button>
            <div className="mt-3 text-[11px] text-slate-500 inline-flex items-center gap-1">
              <Lock className="w-3 h-3" />
              {method === "paypal"
                ? "Secured by PayPal · SSL encrypted"
                : "Payments are encrypted and processed by Stripe."}
            </div>
          </aside>
        </div>
      </div>
    </SiteLayout>
  );
}