import { useEffect, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { CheckCircle2, Download, KeyRound, Package, AlertCircle } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import SiteLayout from "@/components/SiteLayout";
import LoadingSpinner from "@/components/LoadingSpinner";
import { Price } from "@/components/ui/Price";

const client = createClient();

interface OrderItem {
  product_id: number;
  product_name: string;
  product_type: string;
  variant_label: string;
  unit_price: number;
  quantity: number;
  line_total: number;
  download_url: string;
  license_key: string;
}

interface VerifyResult {
  status: string;
  payment_status: string;
  order_id: number;
  order_number: string;
  total: number;
  currency: string;
  items: OrderItem[];
}

export default function PaymentSuccess() {
  const [params] = useSearchParams();
  const sessionId = params.get("session_id") || "";
  // PayPal returns with ?token=<paypal_order_id>&PayerID=...
  const paypalToken = params.get("token") || "";
  const provider = params.get("provider") || (paypalToken ? "paypal" : "stripe");
  const [loading, setLoading] = useState(true);
  const [result, setResult] = useState<VerifyResult | null>(null);
  const [error, setError] = useState<string>("");

  useEffect(() => {
    const verify = async () => {
      try {
        if (provider === "paypal") {
          if (!paypalToken) {
            setError("Missing PayPal order reference.");
            return;
          }
          const res = await client.apiCall.invoke({
            url: "/api/v1/paypal/capture_order",
            method: "POST",
            data: { paypal_order_id: paypalToken },
          });
          setResult(res?.data as VerifyResult);
        } else {
          if (!sessionId) {
            setError("Missing session reference.");
            return;
          }
          const res = await client.apiCall.invoke({
            url: "/api/v1/ecom/verify_payment",
            method: "POST",
            data: { session_id: sessionId },
          });
          setResult(res?.data as VerifyResult);
        }
      } catch (e: any) {
        setError(e?.message || "Failed to verify payment.");
      } finally {
        setLoading(false);
      }
    };
    verify();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId, paypalToken, provider]);

  return (
    <SiteLayout>
      <div className="max-w-3xl mx-auto px-4 md:px-6 py-12 md:py-16">
        {loading ? (
          <div className="py-24 flex flex-col items-center justify-center text-center">
            <LoadingSpinner />
            <p className="text-slate-500 mt-4">Verifying your payment…</p>
          </div>
        ) : error ? (
          <div className="bg-white border border-rose-200 rounded-2xl p-8 text-center">
            <AlertCircle className="w-12 h-12 text-rose-500 mx-auto mb-3" />
            <h1 className="text-2xl font-bold text-slate-900">
              Unable to confirm your payment
            </h1>
            <p className="text-slate-500 mt-2">{error}</p>
            <Link
              to="/shop"
              className="mt-5 inline-block text-[#0b6e3e] font-semibold"
            >
              Return to shop
            </Link>
          </div>
        ) : result ? (
          <>
            <div className="bg-gradient-to-br from-[#0b6e3e] to-[#0a8048] text-white rounded-2xl p-8 text-center shadow-xl">
              <CheckCircle2 className="w-14 h-14 mx-auto text-[#f5c400]" />
              <h1 className="text-3xl font-extrabold mt-3">Thank you for your order!</h1>
              <p className="text-green-50/90 mt-2">
                Order <span className="font-bold">{result.order_number}</span> · Payment {result.payment_status.toUpperCase()}
              </p>
              <div className="mt-3 text-3xl font-extrabold text-[#f5c400]">
                <Price amount={result.total} />
              </div>
            </div>

            <div className="mt-6 bg-white border border-slate-200 rounded-2xl p-6">
              <h2 className="font-bold text-slate-900 flex items-center gap-2">
                <Package className="w-5 h-5 text-[#0b6e3e]" /> Your items
              </h2>
              <div className="mt-4 space-y-3">
                {result.items.map((it, idx) => (
                  <div
                    key={idx}
                    className="border border-slate-200 rounded-xl p-4 flex flex-col gap-2"
                  >
                    <div className="flex items-center justify-between gap-3 flex-wrap">
                      <div>
                        <div className="font-semibold text-slate-900">
                          {it.product_name} × {it.quantity}
                        </div>
                        {it.variant_label && (
                          <div className="text-xs text-slate-500">{it.variant_label}</div>
                        )}
                      </div>
                      <div className="font-bold text-slate-900">
                        <Price amount={it.line_total} />
                      </div>
                    </div>
                    {it.product_type === "digital" && (
                      <div className="flex flex-wrap items-center gap-3 mt-1">
                        {it.download_url && (
                          <a
                            href={it.download_url}
                            target="_blank"
                            rel="noreferrer"
                            className="inline-flex items-center gap-2 text-sm bg-[#0b6e3e] text-white px-3 py-1.5 rounded-lg hover:bg-[#0a8048]"
                          >
                            <Download className="w-4 h-4" /> Download
                          </a>
                        )}
                        {it.license_key && (
                          <div className="inline-flex items-center gap-2 text-sm bg-slate-100 px-3 py-1.5 rounded-lg text-slate-700 font-mono">
                            <KeyRound className="w-4 h-4 text-[#0b6e3e]" />
                            {it.license_key}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>

            <div className="mt-6 flex flex-wrap gap-3 justify-center">
              <Link
                to="/account/orders"
                className="px-5 py-2.5 rounded-xl bg-[#0b6e3e] text-white font-semibold hover:bg-[#0a8048]"
              >
                View order history
              </Link>
              <Link
                to="/shop"
                className="px-5 py-2.5 rounded-xl border border-slate-300 text-slate-700 font-semibold hover:bg-slate-50"
              >
                Continue shopping
              </Link>
            </div>
          </>
        ) : null}
      </div>
    </SiteLayout>
  );
}