import { useState } from "react";
import { AnimatePresence } from "framer-motion";
import { motion } from "framer-motion";
import { FaArrowCircleRight, FaArrowRight, FaCheckCircle, FaLeaf, FaMinus, FaPlus, FaShoppingBag, FaShoppingCart, FaTimes, FaTrash } from "react-icons/fa";
import { Link, router } from "@inertiajs/react";

const MiniCart = ({ cartItems: cartItemsObject, isOpen, onClose }) => {
    const [removingItems, setRemovingItems] = useState(new Set());
    const [updatingQuantities, setUpdatingQuantities] = useState(new Set());

    const cartItems = Object.values(cartItemsObject || {});

    if (!isOpen || !cartItemsObject) return null;

    // Helper function to get the first image from the array
    const getFirstImageUrl = (item) => {
        // Check if image_urls exists and is an array with at least one element
        if (item.attributes && item.attributes.image_urls && Array.isArray(item.attributes.image_urls) && item.attributes.image_urls.length > 0) {
            return item.attributes.image_urls[0];
        }
        
        // Check if image_urls is a string that needs to be parsed
        if (item.attributes && item.attributes.image_urls && typeof item.attributes.image_urls === 'string') {
            try {
                const urls = JSON.parse(item.attributes.image_urls);
                return urls.length > 0 ? urls[0] : null;
            } catch (error) {
                // If parsing fails, return the string itself if it looks like a URL
                return item.attributes.image_urls.startsWith('http') ? item.attributes.image_urls : null;
            }
        }
        
        // Fallback to single image_url if it exists
        if (item.image_url) {
            return item.image_url;
        }
        
        // Default placeholder
        return null;
    };

    const totalItems = cartItems.reduce((sum, item) => sum + item.quantity, 0);
    const totalPrice = cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);

    const handleRemoveItem = (rowId) => {
        setRemovingItems(prev => new Set(prev).add(rowId));
        setTimeout(() => {
            router.delete(route('cart.remove', rowId), { 
                onFinish: () => {
                    setRemovingItems(prev => {
                        const newSet = new Set(prev);
                        newSet.delete(rowId);
                        return newSet;
                    });
                },
                preserveState: false,
            });
        }, 300);
    };

    const handleUpdateQuantity = (rowId, newQuantity) => {
        if (newQuantity < 1) return;
        
        console.log(`Attempting to update item ${rowId} to quantity ${newQuantity}`);
        setUpdatingQuantities(prev => new Set(prev).add(rowId));
        router.patch(route('cart.update', rowId), { quantity: newQuantity }, {
            onSuccess: () => {
                console.log(`Successfully updated item ${rowId} to quantity ${newQuantity}`);
                setUpdatingQuantities(prev => {
                    const newSet = new Set(prev);
                    newSet.delete(rowId);
                    return newSet;
                });
            },
            onError: (errors) => {
                console.error(`Failed to update item ${rowId} to quantity ${newQuantity}:`, errors);
                setUpdatingQuantities(prev => {
                    const newSet = new Set(prev);
                    newSet.delete(rowId);
                    return newSet;
                });
            },
            onFinish: () => {
                console.log(`Update request for item ${rowId} finished.`);
            }
        });
    };
    
    const itemVariants = {
        initial: { opacity: 0, y: 10 },
        animate: { opacity: 1, y: 0 },
        exit: { opacity: 0, x: -50, transition: { duration: 0.2 } },
    };

    return (
        <AnimatePresence>
            {isOpen && (
                <>
                    {/* Backdrop - Removed click handler to prevent closing on backdrop click */}
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        transition={{ duration: 0.2 }}
                        className="fixed inset-0 bg-gray-900 bg-opacity-40 z-40"
                        style={{ pointerEvents: 'none' }} // Prevents any interaction with the backdrop
                    />
                    
                    {/* Cart Panel */}
                    <motion.div
                        initial={{ x: "100%" }}
                        animate={{ x: 0 }}
                        exit={{ x: "100%" }}
                        transition={{ type: "spring", damping: 25, stiffness: 300 }}
                        className="fixed top-0 right-0 h-full w-full sm:w-96 bg-white shadow-2xl z-[9999] flex flex-col"
                        style={{ pointerEvents: 'auto' }}
                    >
                        
                        {/* Header */}
                        <div className="bg-white border-b border-gray-200 p-5 flex items-center justify-between sticky top-0 z-10">
                            <div className="flex items-center text-gray-800">
                                <FaShoppingCart className="mr-3 text-xl text-green-600" />
                                <h3 className="text-xl font-bold">Your Cart</h3>
                                {totalItems > 0 && (
                                    <span className="ml-3 bg-green-500 text-white text-xs font-extrabold px-2.5 py-1 rounded-full shadow-md">
                                        {totalItems} Items
                                    </span>
                                )}
                            </div>
                            <button 
                                onClick={onClose} 
                                className="text-gray-500 hover:text-red-500 p-2 rounded-full transition-colors"
                                aria-label="Close cart"
                            >
                                <FaTimes className="text-xl" />
                            </button>
                        </div>

                        {/* Cart Items */}
                        <div className="flex-1 overflow-y-auto p-4 bg-gray-50">
                            {cartItems.length === 0 ? (
                                <div className="flex flex-col items-center justify-center h-full text-gray-500 py-8">
                                    <div className="bg-green-100 p-6 rounded-full mb-4">
                                        <FaShoppingCart className="text-5xl text-green-500" />
                                    </div>
                                    <h4 className="text-xl font-medium text-gray-700 mb-2">Your cart is empty</h4>
                                    <p className="text-sm text-gray-500 mb-6 text-center max-w-xs">
                                        Looks like you haven't added any products to your cart yet.
                                    </p>
                                    <button 
                                        onClick={onClose}
                                        className="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded-lg font-medium transition-colors flex items-center"
                                    >
                                        Continue Shopping
                                        <FaArrowRight className="ml-2" />
                                    </button>
                                </div>
                            ) : (
                                <motion.div 
                                    className="space-y-4"
                                    initial="initial"
                                    animate="animate"
                                    variants={{ animate: { transition: { staggerChildren: 0.05 } } }}
                                >
                                    {cartItems.map(item => (
                                        <motion.div
                                            key={item.rowId}
                                            variants={itemVariants}
                                            className={`flex p-3 bg-gray-50 border border-gray-100 rounded-xl transition-all duration-300 ${removingItems.has(item.rowId) ? 'opacity-40 blur-sm' : 'opacity-100'}`}
                                        >
                                            
                                            {/* Product Image */}
                                            <div className="w-16 h-16 bg-white rounded-lg overflow-hidden flex-shrink-0 mr-4 shadow-sm border border-gray-200">
                                                {getFirstImageUrl(item) ? (
                                                    <img 
                                                        src={getFirstImageUrl(item)} 
                                                        alt={item.name} 
                                                        className="w-full h-full object-cover"
                                                    />
                                                ) : (
                                                    <div className="w-full h-full flex items-center justify-center bg-gray-100">
                                                        <FaLeaf className="text-gray-400 text-xl" />
                                                    </div>
                                                )}
                                            </div>
                                            
                                            {/* Product Details & Controls */}
                                            <div className="flex-1 min-w-0">
                                                <h4 className="font-semibold text-gray-900 text-sm mb-1 truncate">{item.name}</h4>
                                                
                                                {/* Price & Subtotal */}
                                                <p className="text-green-700 font-extrabold text-sm mb-2">
                                                    ₵{(item.price)}
                                                    <span className="text-gray-500 font-normal text-xs ml-2">
                                                        / Item
                                                    </span>
                                                </p>
                                                
                                                {/* Quantity Controls */}
                                                <div className="flex items-center justify-between">
                                                    <div className="flex items-center border border-gray-300 rounded-full bg-white">
                                                        <button
                                                            onClick={() => handleUpdateQuantity(item.rowId, item.quantity - 1)}
                                                            disabled={item.quantity <= 1 || updatingQuantities.has(item.rowId)}
                                                            className="w-6 h-6 rounded-full text-gray-600 hover:bg-gray-200 flex items-center justify-center transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
                                                        >
                                                            <FaMinus className="text-xs" />
                                                        </button>
                                                        
                                                        <span className="mx-2 text-sm font-bold w-6 text-center text-gray-800">
                                                            {updatingQuantities.has(item.rowId) ? (
                                                                <div className="w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full animate-spin mx-auto"></div>
                                                            ) : (
                                                                item.quantity
                                                            )}
                                                        </span>
                                                        
                                                        <button
                                                            onClick={() => handleUpdateQuantity(item.rowId, item.quantity + 1)}
                                                            disabled={updatingQuantities.has(item.rowId)}
                                                            className="w-6 h-6 rounded-full text-gray-600 hover:bg-gray-200 flex items-center justify-center transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
                                                        >
                                                            <FaPlus className="text-xs" />
                                                        </button>
                                                    </div>

                                                    {/* Total for Item & Remove Button */}
                                                    <div className="flex items-center space-x-3">
                                                         <span className="text-sm font-extrabold text-gray-900">
                                                            ₵{(item.price * item.quantity)}
                                                        </span>
                                                        <button
                                                            onClick={(e) => {
                                                                e.stopPropagation(); 
                                                                handleRemoveItem(item.rowId);
                                                            }}
                                                            type="button"
                                                            disabled={removingItems.has(item.rowId)}
                                                            className="text-gray-400 hover:text-red-500 transition-colors p-1 rounded-full hover:bg-red-50 disabled:opacity-50"
                                                            aria-label="Remove item"
                                                        >
                                                            {removingItems.has(item.rowId) ? (
                                                                <div className="w-4 h-4 border-2 border-red-500 border-t-transparent rounded-full animate-spin"></div>
                                                            ) : (
                                                                <FaTrash className="w-4 h-4" />
                                                            )}
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </motion.div>
                                    ))}
                                </motion.div>
                            )}
                        </div>

                        {/* Footer - Checkout & Totals */}
                        {cartItems.length > 0 && (
                            <div className="bg-white border-t border-gray-200 p-5 sticky bottom-0 shadow-2xl">
                                
                                <div className="flex items-center text-green-600 text-sm mb-4 bg-green-50 p-3 rounded-lg font-medium">
                                    <FaCheckCircle className="mr-2 text-lg flex-shrink-0" />
                                    <span>
                                        **You qualify for free shipping!**
                                    </span>
                                </div>

                                <div className="flex justify-between items-center mb-4 pt-2 border-t border-dashed border-gray-300">
                                    <span className="text-lg font-semibold text-gray-700">Order Subtotal</span>
                                    <span className="text-2xl font-extrabold text-gray-900">₵{totalPrice}</span>
                                </div>
                                
                                <div className="space-y-3">
                                    <Link 
                                        href={route('cart.view')} 
                                        className="block w-full bg-green-600 hover:bg-green-700 text-white text-center py-3 rounded-xl font-extrabold transition-transform duration-200 transform hover:scale-[1.01] flex items-center justify-center shadow-lg shadow-green-200"
                                    >
                                        Proceed to Checkout
                                        <FaArrowCircleRight className="ml-2 text-lg" />
                                    </Link>
                                    
                                    <button
                                        onClick={onClose}
                                        className="block w-full bg-white border border-gray-300 hover:bg-gray-100 text-gray-700 text-center py-3 rounded-xl font-semibold transition-colors flex items-center justify-center"
                                    >
                                        <FaShoppingBag className="mr-2" />
                                        Continue Shopping
                                    </button>
                                </div>
                            </div>
                        )}
                    </motion.div>
                </>
            )}
        </AnimatePresence>
    );
};

export default MiniCart;