"use client";
import { useEffect, useState } from "react";
import { useAppSelector } from "@/store/hooks";
import { useRouter, useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import {
  CheckCircle,
  Download,
  ShoppingBag,
  Clock,
  ArrowRight,
  Package,
  Copy,
  Check,
} from "lucide-react";
import { usePayment } from "@/lib/PaymentContext";
import { formatDate } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";

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-[140px]">{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 { lastCompletedOrder } = usePayment();
  const isCOD = searchParams.get("method") === "cod";

  const order = lastCompletedOrder;
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);

  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>

            {/* Radiate rings */}
            {[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"
          >
            {isCOD ? "Order Placed!" : "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"
          >
            {isCOD
              ? "Your COD order is placed. The seller will confirm after receiving payment."
              : "Your payment was processed successfully. You're protected by Doliplay Buyer Guarantee."}
          </motion.p>
        </div>

        {/* Order details card */}
        <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">Transaction Details</p>
          </div>
          <div className="px-5 py-2">
            {order ? (
              <>
                <CopyField label="Order ID" value={order.id.toUpperCase()} />
                {order.transactionId && (
                  <CopyField label="Transaction ID" value={order.transactionId} />
                )}
                <CopyField label="Amount Paid" value={formatPrice(order.totalAmount)} />
                <CopyField
                  label="Payment Method"
                  value={order.paymentMethod === "paypal" ? "PayPal" : "Cash on Delivery"}
                />
                <CopyField label="Date & Time" value={formatDate(order.createdAt)} />
              </>
            ) : (
              <>
                <CopyField label="Order ID" value="ORD-DEMO-001" />
                <CopyField label="Amount Paid" value={`${currencyCode}69,904`} />
                <CopyField label="Payment Method" value={isCOD ? "Cash on Delivery" : "PayPal"} />
                <CopyField label="Date & Time" value={formatDate(new Date().toISOString())} />
              </>
            )}
          </div>
        </motion.div>

        {isCOD && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.7 }}
            className="flex gap-3 p-4 rounded-xl mb-5"
            style={{ background: "rgba(251,146,60,0.08)", border: "1px solid rgba(251,146,60,0.2)" }}
          >
            <Clock size={14} className="text-orange-400 shrink-0 mt-0.5" />
            <p className="text-xs text-orange-400 leading-relaxed">
              <strong>Next step:</strong> Arrange a meeting with the seller. Pay cash after inspecting the item. The seller will mark payment as received.
            </p>
          </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/profile")}
            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)" }}
          >
            <Clock size={15} />
            View Payment History
          </button>

          <div className="grid grid-cols-2 gap-3">
            <button
              onClick={() => router.push(`/marketplace/payment/receipt/${order?.id ?? "demo"}`)}
              className="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)" }}
            >
              <Download size={14} />
              Receipt
            </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)] hover:text-[var(--text-primary)] transition-colors"
              style={{ background: "var(--card)" }}
            >
              <ShoppingBag size={14} />
              Shop More
            </button>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
