// components/UPIPaymentModal.tsx
"use client";

import { useEffect, useState } from "react";
import { QRCodeSVG } from "qrcode.react";
import { motion, AnimatePresence } from "framer-motion";
import { X, CheckCircle2, Loader2, Smartphone, ShieldCheck, ArrowRight } from "lucide-react";
import { useRouter } from "next/navigation";
import { useCartStore } from "@/store/useCartStore";

interface UPIPaymentModalProps {
  isOpen: boolean;
  onClose: () => void;
  orderData: {
    orderId: string;
    dbOrderId: string;
    amount: number;
    upiUri: string;
  } | null;
}

export default function UPIPaymentModal({ isOpen, onClose, orderData }: UPIPaymentModalProps) {
  const router = useRouter();
  const { clearCart } = useCartStore();
  const [checking, setChecking] = useState(false);
  const [isPaid, setIsPaid] = useState(false);

  useEffect(() => {
    let interval: any;
    if (isOpen && orderData?.orderId && !isPaid) {
      // Auto-poll Paytm status every 3 seconds
      interval = setInterval(async () => {
        try {
          const res = await fetch("/api/payment/verify", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ orderId: orderData.orderId }),
          });
          const data = await res.json();
          if (data.status === "COMPLETED") {
            setIsPaid(true);
            clearCart();
            clearInterval(interval);
            setTimeout(() => {
              onClose();
              router.push("/orders");
              router.refresh();
            }, 1800);
          }
        } catch (e) {
          console.error(e);
        }
      }, 3000);
    }
    return () => clearInterval(interval);
  }, [isOpen, orderData, isPaid, clearCart, onClose, router]);

  const handleManualCheck = async () => {
    if (!orderData?.orderId) return;
    setChecking(true);
    try {
      const res = await fetch("/api/payment/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orderId: orderData.orderId }),
      });
      const data = await res.json();
      if (data.status === "COMPLETED") {
        setIsPaid(true);
        clearCart();
        setTimeout(() => {
          onClose();
          router.push("/orders");
          router.refresh();
        }, 1500);
      } else {
        alert("Payment not confirmed yet. If already paid, please wait 5-10 seconds.");
      }
    } catch {
      alert("Error checking status.");
    } finally {
      setChecking(false);
    }
  };

  return (
    <AnimatePresence>
      {isOpen && orderData && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="absolute inset-0 bg-black/80 backdrop-blur-sm"
          />

          <motion.div
            initial={{ scale: 0.95, opacity: 0, y: 15 }}
            animate={{ scale: 1, opacity: 1, y: 0 }}
            exit={{ scale: 0.95, opacity: 0, y: 15 }}
            className="relative w-full max-w-sm rounded-3xl bg-zinc-900 border border-zinc-800 p-6 shadow-2xl z-10 text-center"
          >
            <button
              onClick={onClose}
              className="absolute top-4 right-4 text-zinc-400 hover:text-white transition"
            >
              <X className="h-5 w-5" />
            </button>

            {isPaid ? (
              <div className="py-8 space-y-4">
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  className="h-16 w-16 bg-emerald-500/20 text-emerald-400 rounded-full flex items-center justify-center mx-auto"
                >
                  <CheckCircle2 className="h-10 w-10" />
                </motion.div>
                <h3 className="text-xl font-bold text-white">Payment Successful!</h3>
                <p className="text-xs text-zinc-400">Unlocking files & redirecting to downloads...</p>
              </div>
            ) : (
              <div className="space-y-5">
                <div>
                  <span className="inline-block px-3 py-1 rounded-full bg-indigo-500/10 text-indigo-400 text-xs font-bold mb-2">
                    UPI Instant Payment
                  </span>
                  <h3 className="text-2xl font-black text-white">₹{orderData.amount.toFixed(2)}</h3>
                  <p className="text-[11px] text-zinc-500 mt-0.5">Order Ref: {orderData.orderId}</p>
                </div>

                {/* Dynamic QR Code Canvas */}
                <div className="p-4 bg-white rounded-2xl inline-block shadow-inner">
                  <QRCodeSVG value={orderData.upiUri} size={180} level="M" />
                </div>

                {/* Mobile Intent Button */}
                <div className="block sm:hidden">
                  <a
                    href={orderData.upiUri}
                    className="w-full flex items-center justify-center gap-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold py-3 transition shadow-lg shadow-indigo-600/30"
                  >
                    <Smartphone className="h-4 w-4" /> Pay with GPay / PhonePe / Paytm
                  </a>
                </div>

                <div className="text-xs text-zinc-400 space-y-1">
                  <p className="font-medium text-zinc-300">Scan using any UPI App</p>
                  <p className="text-[10px] text-zinc-500 flex items-center justify-center gap-1">
                    <ShieldCheck className="h-3.5 w-3.5 text-emerald-400" /> Auto-verified via Paytm gateway
                  </p>
                </div>

                <button
                  onClick={handleManualCheck}
                  disabled={checking}
                  className="w-full flex items-center justify-center gap-2 rounded-xl bg-zinc-800 hover:bg-zinc-700 text-zinc-200 text-xs font-semibold py-2.5 transition"
                >
                  {checking ? <Loader2 className="h-4 w-4 animate-spin" /> : "I Have Paid / Check Status"}
                </button>
              </div>
            )}
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
}