"use client";
import { useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import {
  XCircle,
  RefreshCw,
  MessageCircle,
  ArrowLeft,
  AlertTriangle,
  ShoppingBag,
} from "lucide-react";
import { orderService } from "@/services/orderService";

export function PaymentFailed() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const markedFailed = useRef(false);

  // URL params:
  //   cancelled    = "1" when user clicked Cancel on PayPal
  //   orderId      = backend order ID (so we can mark it failed)
  //   listingSlug  = slug of the product listing to go back to
  const isCancelled = searchParams.get("cancelled") === "1";
  const backendOrderId = searchParams.get("orderId");
  const listingSlug = searchParams.get("listingSlug") ?? "";

  // Mark the backend order as failed (payment_status = 2) on arrival
  useEffect(() => {
    if (!backendOrderId || markedFailed.current) return;
    markedFailed.current = true;
    orderService
      .confirmOrderPayment(Number(backendOrderId), 2)
      .catch(() => {});
  }, [backendOrderId]);

  const title = isCancelled ? "Payment Cancelled" : "Payment Failed";
  const subtitle = isCancelled
    ? "You cancelled the PayPal checkout. Your order has not been charged."
    : "Don't worry — your order was not charged.";

  const handleRetry = () => {
    if (listingSlug) {
      router.push(`/marketplace/listing/${listingSlug}`);
    } else {
      router.push("/marketplace");
    }
  };

  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">
        {/* Icon */}
        <div className="flex flex-col items-center mb-8">
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: "spring", stiffness: 260, damping: 18 }}
            className="w-24 h-24 rounded-full flex items-center justify-center mb-6"
            style={{ background: "rgba(248,113,113,0.12)" }}
          >
            <motion.div
              animate={isCancelled ? {} : { x: [0, -6, 6, -4, 4, 0] }}
              transition={{ duration: 0.5, delay: 0.4 }}
            >
              <XCircle size={52} className="text-red-400" />
            </motion.div>
          </motion.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"
          >
            {title}
          </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"
          >
            {subtitle}
          </motion.p>
        </div>

        {/* Reason / info card */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.6 }}
          className="flex gap-3 p-4 rounded-xl mb-6"
          style={{
            background: "rgba(248,113,113,0.08)",
            border: "1px solid rgba(248,113,113,0.2)",
          }}
        >
          <AlertTriangle size={15} className="text-red-400 shrink-0 mt-0.5" />
          <div>
            <p className="text-xs font-semibold text-red-400 mb-0.5">
              {isCancelled ? "What happened?" : "Reason"}
            </p>
            <p className="text-xs text-[var(--text-muted)]">
              {isCancelled
                ? "You left the PayPal checkout before completing the payment. No charge was made."
                : "Your payment was declined by your bank or payment provider."}
            </p>
          </div>
        </motion.div>

        {/* Common causes (only for failures, not cancellations) */}
        {!isCancelled && (
          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.7 }}
            className="rounded-2xl overflow-hidden border border-[var(--border)] mb-6"
            style={{ background: "var(--card)" }}
          >
            <p className="px-5 py-3 text-xs font-semibold text-[var(--text-muted)] border-b border-[var(--border)]">
              Common Causes
            </p>
            {[
              "Insufficient balance in your account",
              "Card declined by your bank",
              "Incorrect payment details",
              "Transaction limit exceeded",
            ].map((cause, i) => (
              <div
                key={i}
                className="flex items-center gap-3 px-5 py-3 border-b border-[var(--border)] last:border-0"
              >
                <div
                  className="w-1.5 h-1.5 rounded-full shrink-0"
                  style={{ background: "rgba(248,113,113,0.6)" }}
                />
                <p className="text-xs text-[var(--text-muted)]">{cause}</p>
              </div>
            ))}
          </motion.div>
        )}

        {/* Actions */}
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: isCancelled ? 0.7 : 0.85 }}
          className="space-y-3"
        >
          {/* Primary: go back to the listing so the buyer can try again */}
          <button
            onClick={handleRetry}
            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)" }}
          >
            <RefreshCw size={15} />
            {listingSlug ? "Back to Listing" : "Browse Marketplace"}
          </button>

          <div className="grid grid-cols-2 gap-3">
            <button
              onClick={() => router.push("/marketplace/messages")}
              className="py-3 rounded-xl text-sm font-medium flex items-center justify-center gap-2 border border-[var(--border)] text-[var(--text-muted)]"
              style={{ background: "var(--card)" }}
            >
              <MessageCircle size={14} />
              Support
            </button>
            <button
              onClick={() => router.push("/marketplace")}
              className="py-3 rounded-xl text-sm font-medium flex items-center justify-center gap-2 border border-[var(--border)] text-[var(--text-muted)]"
              style={{ background: "var(--card)" }}
            >
              <ShoppingBag size={14} />
              Marketplace
            </button>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
