"use client";
import { useEffect, useState, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import {
  CheckCircle,
  ShoppingBag,
  ArrowRight,
  Copy,
  Check,
  Loader2,
  AlertCircle,
  Package,
} from "lucide-react";
import { orderService } from "@/services/orderService";
import type { MarketplaceOrder } from "@/services/orderService";
import { useFormatPrice } from "@/hooks/useFormatPrice";

const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? "";

function CopyField({ label, value }: { label: string; value: string }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(value).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <div className="flex items-center justify-between py-2.5 border-b border-[var(--border)] last:border-0">
      <span className="text-xs text-[var(--text-muted)]">{label}</span>
      <div className="flex items-center gap-2">
        <span className="text-xs font-mono text-[var(--text-primary)] truncate max-w-[160px]">
          {value}
        </span>
        <button
          onClick={copy}
          className="p-1 rounded-lg hover:bg-[var(--card)] transition-colors"
        >
          {copied ? (
            <Check size={12} className="text-green-400" />
          ) : (
            <Copy size={12} className="text-[var(--text-muted)]" />
          )}
        </button>
      </div>
    </div>
  );
}

export function PaymentSuccess() {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const searchParams = useSearchParams();
  const hasCaptured = useRef(false);

  // URL params set by PayPal on redirect back:
  //   token     = PayPal order ID  (added by PayPal)
  //   PayerID   = PayPal payer ID  (added by PayPal)
  //   orderId   = our backend order ID  (we set this when building the return URL)
  const paypalToken = searchParams.get("token");
  const backendOrderId = searchParams.get("orderId");

  const [capturing, setCapturing] = useState(!!paypalToken);
  const [captureError, setCaptureError] = useState("");
  const [order, setOrder] = useState<MarketplaceOrder | null>(null);

  useEffect(() => {
    if (!paypalToken || !backendOrderId || hasCaptured.current) return;
    hasCaptured.current = true;

    const run = async () => {
      setCapturing(true);
      setCaptureError("");
      try {
        // 1. Capture the PayPal payment server-side
        const captureRes = await fetch(`${BASE_PATH}/api/paypal/capture-order`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ orderId: paypalToken }),
        });
        const captureData = await captureRes.json();
        if (!captureRes.ok || !captureData.success) {
          throw new Error(captureData.error ?? "Payment capture failed.");
        }
        const captureId: string = captureData.captureId as string;

        // 2. Confirm the backend order with the capture ID
        await orderService.confirmOrderPayment(
          Number(backendOrderId),
          1,
          captureId,
        );

        // 3. Fetch the confirmed order details
        const confirmed = await orderService.getOrderDetail(
          Number(backendOrderId),
        );
        setOrder(confirmed);
      } catch (err) {
        setCaptureError(
          err instanceof Error ? err.message : "Payment confirmation failed.",
        );
        // Mark the backend order as failed so it doesn't stay pending forever
        try {
          await orderService.confirmOrderPayment(Number(backendOrderId), 2);
        } catch {
          // best-effort
        }
      } finally {
        setCapturing(false);
      }
    };

    run();
  }, [paypalToken, backendOrderId]);

  /* ── Capturing state ── */
  if (capturing) {
    return (
      <div
        className="min-h-full flex flex-col items-center justify-center px-4 py-12"
        style={{ background: "var(--bg)" }}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="flex flex-col items-center gap-4"
        >
          <div
            className="w-20 h-20 rounded-full flex items-center justify-center"
            style={{ background: "rgba(16,185,129,0.1)" }}
          >
            <Loader2 size={36} className="text-green-400 animate-spin" />
          </div>
          <p className="text-base font-bold text-[var(--text-primary)]">
            Confirming your payment…
          </p>
          <p className="text-sm text-[var(--text-muted)] text-center max-w-xs">
            Please wait — do not close or refresh this page.
          </p>
        </motion.div>
      </div>
    );
  }

  /* ── Capture error state ── */
  if (captureError) {
    return (
      <div
        className="min-h-full flex flex-col items-center justify-center px-4 py-12"
        style={{ background: "var(--bg)" }}
      >
        <div className="w-full max-w-md">
          <div className="flex flex-col items-center mb-8">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center mb-5"
              style={{ background: "rgba(244,63,94,0.1)" }}
            >
              <AlertCircle size={40} className="text-red-400" />
            </div>
            <h1 className="text-xl font-black text-[var(--text-primary)] mb-2">
              Payment Confirmation Failed
            </h1>
            <p className="text-sm text-[var(--text-muted)] text-center max-w-xs">
              {captureError}
            </p>
          </div>
          <div className="space-y-3">
            <button
              onClick={() => router.push("/marketplace")}
              className="w-full py-3.5 rounded-xl text-white font-semibold text-sm flex items-center justify-center gap-2"
              style={{ background: "var(--accent)" }}
            >
              <ShoppingBag size={15} />
              Back to Marketplace
            </button>
            <button
              onClick={() => router.push("/marketplace/orders")}
              className="w-full py-3.5 rounded-xl text-sm font-semibold flex items-center justify-center gap-2 border border-[var(--border)] text-[var(--text-primary)]"
              style={{ background: "var(--card)" }}
            >
              <Package size={15} />
              View My Orders
            </button>
          </div>
          <p className="text-[10px] text-center mt-4 text-[var(--text-muted)]">
            If your PayPal account was charged, please contact support with
            Order ID: {backendOrderId ?? "—"}
          </p>
        </div>
      </div>
    );
  }

  /* ── Success state ── */
  const orderId = order?.id ?? backendOrderId ?? "—";
  const transactionId = order?.transactionId ?? paypalToken ?? "";
  const amountPaid = order
    ? formatPrice(order.price * order.quantity)
    : "—";
  const createdAt = order?.createdAt
    ? new Date(order.createdAt).toLocaleString()
    : new Date().toLocaleString();

  return (
    <div
      className="min-h-full flex flex-col items-center justify-center px-4 py-12"
      style={{ background: "var(--bg)" }}
    >
      <div className="w-full max-w-md">
        {/* Success animation */}
        <div className="flex flex-col items-center mb-8">
          <div className="relative mb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{
                type: "spring",
                stiffness: 260,
                damping: 20,
                delay: 0.1,
              }}
              className="w-24 h-24 rounded-full flex items-center justify-center"
              style={{ background: "rgba(34,197,94,0.12)" }}
            >
              <motion.div
                initial={{ scale: 0, rotate: -90 }}
                animate={{ scale: 1, rotate: 0 }}
                transition={{
                  type: "spring",
                  stiffness: 300,
                  damping: 22,
                  delay: 0.3,
                }}
              >
                <CheckCircle size={52} className="text-green-400" />
              </motion.div>
            </motion.div>

            {[1, 2].map((i) => (
              <motion.div
                key={i}
                className="absolute inset-0 rounded-full"
                style={{ border: "2px solid rgba(34,197,94,0.3)" }}
                initial={{ scale: 1, opacity: 0.6 }}
                animate={{ scale: 1 + i * 0.5, opacity: 0 }}
                transition={{
                  duration: 1.5,
                  repeat: Infinity,
                  delay: i * 0.4,
                  ease: "easeOut",
                }}
              />
            ))}
          </div>

          <motion.h1
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 }}
            className="text-2xl font-black text-[var(--text-primary)] mb-2"
          >
            Payment Successful!
          </motion.h1>
          <motion.p
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
            className="text-sm text-[var(--text-muted)] text-center max-w-xs"
          >
            Your payment was processed successfully. You&apos;re protected by
            Doliplay Buyer Guarantee.
          </motion.p>
        </div>

        {/* Order details */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.6 }}
          className="rounded-2xl overflow-hidden border border-[var(--border)] mb-5"
          style={{ background: "var(--card)" }}
        >
          <div
            className="px-5 py-3 border-b border-[var(--border)]"
            style={{ background: "rgba(34,197,94,0.06)" }}
          >
            <p className="text-xs font-semibold text-green-400">
              Order Confirmation
            </p>
          </div>
          <div className="px-5 py-2">
            <CopyField label="Order ID" value={String(orderId)} />
            {transactionId && (
              <CopyField label="Transaction ID" value={transactionId} />
            )}
            <CopyField label="Amount Paid" value={amountPaid} />
            <CopyField label="Payment Method" value="PayPal" />
            <CopyField label="Date & Time" value={createdAt} />
          </div>
        </motion.div>

        {/* Action buttons */}
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.8 }}
          className="space-y-3"
        >
          <button
            onClick={() =>
              router.push(
                `/marketplace/orders/${order?.id ?? backendOrderId ?? ""}`,
              )
            }
            className="w-full py-3.5 rounded-xl text-white font-semibold text-sm flex items-center justify-center gap-2"
            style={{ background: "var(--accent)" }}
          >
            <Package size={15} />
            View My Order
            <ArrowRight size={14} />
          </button>

          <button
            onClick={() => router.push("/marketplace")}
            className="w-full py-3 rounded-xl text-sm font-medium flex items-center justify-center gap-2 border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
            style={{ background: "var(--card)" }}
          >
            <ShoppingBag size={14} />
            Continue Shopping
          </button>
        </motion.div>
      </div>
    </div>
  );
}
