// components/CartDrawer.tsx
"use client";

import { useState } from "react";
import { useCartStore } from "@/store/useCartStore";
import { useAuthModalStore } from "@/store/useAuthModalStore";
import { useSession } from "next-auth/react";
import { X, Trash2, ArrowRight, Loader2, ShieldCheck } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import UPIPaymentModal from "@/components/UPIPaymentModal";

export default function CartDrawer() {
  const { items, isOpen, setOpen, removeItem, getTotal } = useCartStore();
  const { data: session } = useSession();
  const { openModal } = useAuthModalStore();

  const [loading, setLoading] = useState(false);
  const [paymentOrder, setPaymentOrder] = useState<any>(null);
  const [showPaymentModal, setShowPaymentModal] = useState(false);

  const handleCheckout = async () => {
    // 1. Check if user is logged in
    if (!session?.user) {
      setOpen(false); // Close cart
      openModal("login"); // Open login modal seamlessly
      return;
    }

    setLoading(true);
    try {
      const res = await fetch("/api/payment/create-order", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create order");

      setPaymentOrder(data);
      setOpen(false);
      setShowPaymentModal(true);
    } catch (err: any) {
      alert(err.message || "Checkout failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <AnimatePresence>
        {isOpen && (
          <div className="fixed inset-0 z-50 overflow-hidden">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setOpen(false)}
              className="absolute inset-0 bg-black/60 backdrop-blur-sm"
            />

            <motion.div
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", damping: 25, stiffness: 200 }}
              className="absolute right-0 top-0 h-full w-full max-w-md bg-zinc-900 border-l border-zinc-800 p-6 flex flex-col justify-between shadow-2xl"
            >
              <div>
                <div className="flex items-center justify-between border-b border-zinc-800 pb-4">
                  <h3 className="text-lg font-semibold text-white">Your Cart ({items.length})</h3>
                  <button onClick={() => setOpen(false)} className="text-zinc-400 hover:text-white">
                    <X className="h-5 w-5" />
                  </button>
                </div>

                <div className="mt-4 space-y-4 max-h-[60vh] overflow-y-auto pr-1">
                  {items.length === 0 ? (
                    <p className="text-zinc-500 text-center py-10 text-sm">Your cart is empty.</p>
                  ) : (
                    items.map((item) => (
                      <div key={item.id} className="flex items-center gap-4 bg-zinc-950/50 p-3 rounded-xl border border-zinc-800/80">
                        <div className="relative h-14 w-14 rounded-lg overflow-hidden bg-zinc-800 flex-shrink-0">
                          <Image src={item.thumbnailUrl} alt={item.title} fill className="object-cover" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <h4 className="text-sm font-medium text-white truncate">{item.title}</h4>
                          <span className="inline-block px-1.5 py-0.5 rounded text-[10px] font-bold bg-indigo-500/20 text-indigo-400 mt-1">
                            {item.fileType}
                          </span>
                          <p className="text-sm font-semibold text-zinc-200 mt-1">₹{item.price.toFixed(2)}</p>
                        </div>
                        <button onClick={() => removeItem(item.id)} className="text-zinc-500 hover:text-rose-400 p-1">
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    ))
                  )}
                </div>
              </div>

              {items.length > 0 && (
                <div className="border-t border-zinc-800 pt-4 space-y-3">
                  <div className="flex justify-between items-center text-zinc-400">
                    <span className="text-sm">Total Amount</span>
                    <span className="text-xl font-bold text-white">₹{getTotal().toFixed(2)}</span>
                  </div>

                  <button
                    onClick={handleCheckout}
                    disabled={loading}
                    className="w-full flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-500 text-white font-medium py-3 rounded-xl transition shadow-lg shadow-indigo-600/30 disabled:opacity-50 text-sm"
                  >
                    {loading ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <>
                        Pay with UPI (Instant Delivery) <ArrowRight className="h-4 w-4" />
                      </>
                    )}
                  </button>
                </div>
              )}
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      <UPIPaymentModal
        isOpen={showPaymentModal}
        onClose={() => setShowPaymentModal(false)}
        orderData={paymentOrder}
      />
    </>
  );
}