'use client';

import { motion, AnimatePresence } from 'framer-motion';
import { 
  X, 
  ShoppingCart, 
  Heart, 
  Trash2, 
  Plus, 
  Minus, 
  ArrowRight, 
  ExternalLink, 
  Sparkles, 
  Shield,
  MoveRight,
  ShoppingBag,
  Star,
  Crown
} from 'lucide-react';
import { useSidebar } from '@/contexts/SidebarContext';
import { useCart, CartItem } from '@/hooks/useCart';
import { useWishlist, WishlistItem } from '@/hooks/useWishlist';
import { useRef } from 'react';
import { useRouter } from 'next/navigation';

export default function GlobalSidebar() {
  const { isSidebarOpen, sidebarType, closeSidebar } = useSidebar();
  const { 
    items: cartItems, 
    removeItem, 
    updateQuantity, 
    getTotalPrice, 
    clearCart, 
    addWebsite: addToCart 
  } = useCart();
  const { 
    items: wishlistItems, 
    removeItem: removeWishlistItem, 
    moveToCart, 
    moveAllToCart,
  } = useWishlist();

  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const items = sidebarType === 'cart' ? cartItems : wishlistItems;
  const totalPrice = getTotalPrice();

  const router = useRouter();

  const handleCheckout = () => {
    closeSidebar();
    router.push("/cart")
  };

  // Simplified - just pass the addToCart function, moveToCart handles the rest
  const handleMoveToCart = (websiteId: string) => {
    moveToCart(websiteId, addToCart);
  };

  const handleMoveAllToCart = () => {
    moveAllToCart(addToCart);
  };

  const getDAColor = (da: number) => {
    if (da >= 90) return 'text-emerald-600';
    if (da >= 80) return 'text-blue-600';
    if (da >= 70) return 'text-amber-600';
    return 'text-rose-600';
  };

  const getAuthorityBadge = (da: number) => {
    if (da >= 90) return { color: 'from-emerald-500 to-teal-500', text: 'Elite' };
    if (da >= 80) return { color: 'from-blue-500 to-cyan-500', text: 'Premium' };
    if (da >= 70) return { color: 'from-amber-500 to-orange-500', text: 'Quality' };
    return { color: 'from-gray-500 to-slate-500', text: 'Standard' };
  };

  // Animation variants
  const sidebarVariants = {
    closed: {
      x: '100%',
      transition: {
        type: 'spring' as const,
        damping: 40,
        stiffness: 400
      }
    },
    open: {
      x: 0,
      transition: {
        type: 'spring' as const,
        damping: 40,
        stiffness: 400,
        staggerChildren: 0.1
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, x: 20 },
    visible: { 
      opacity: 1, 
      x: 0,
      transition: {
        type: "spring" as const,
        stiffness: 300,
        damping: 24
      }
    }
  };

  return (
    <AnimatePresence>
      {isSidebarOpen && (
        <>
          {/* Sophisticated Overlay */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-slate-900/70 backdrop-blur-md z-90"
            onClick={closeSidebar}
          />

          {/* Elegant Sidebar */}
          <motion.div
            variants={sidebarVariants}
            initial="closed"
            animate="open"
            exit="closed"
            className="fixed top-0 right-0 h-full w-full max-w-md bg-white shadow-2xl z-101 flex flex-col border-l border-slate-200"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Premium Header - Fixed */}
            <div className="relative bg-linear-to-br from-slate-50 via-white to-blue-50/30 border-b border-slate-200/60 p-6 shrink-0">
              <div className="absolute inset-0 bg-linear-to-br from-white/80 to-blue-50/20 backdrop-blur-sm"></div>
              
              <div className="relative flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-white rounded-2xl shadow-lg border border-slate-200/60">
                    {sidebarType === 'cart' ? (
                      <ShoppingCart className="h-6 w-6 text-slate-700" />
                    ) : (
                      <Heart className="h-6 w-6 text-rose-500" />
                    )}
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-slate-800">
                      {sidebarType === 'cart' ? 'Shopping Cart' : 'Wishlist'}
                    </h2>
                    <p className="text-slate-600 text-sm mt-1">
                      {items.length} {items.length === 1 ? 'premium item' : 'premium items'}
                    </p>
                  </div>
                </div>
                
                <button
                  onClick={closeSidebar}
                  className="p-3 hover:bg-slate-100 rounded-2xl transition-all duration-300 group border border-slate-200/60"
                >
                  <X className="h-5 w-5 text-slate-600 group-hover:text-slate-800 transition-colors" />
                </button>
              </div>
              
              {/* Decorative elements */}
              <div className="absolute top-4 right-20">
                <Sparkles className="h-4 w-4 text-blue-400/60" />
              </div>
            </div>

            {/* Content Area - Scrollable with mouse wheel support */}
            <div 
              ref={scrollContainerRef}
              className="flex-1 overflow-y-auto bg-slate-50/30"
              style={{
                scrollbarWidth: 'thin',
                scrollbarColor: '#cbd5e1 #f1f5f9',
                overscrollBehavior: 'contain',
              }}
              tabIndex={0}
            >
              {items.length === 0 ? (
                <motion.div 
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  className="flex flex-col items-center justify-center h-full text-center p-8"
                >
                  <div className="relative mb-8">
                    <div className="w-24 h-24 bg-linear-to-br from-slate-100 to-slate-200 rounded-3xl flex items-center justify-center shadow-inner">
                      {sidebarType === 'cart' ? (
                        <ShoppingCart className="h-12 w-12 text-slate-400" />
                      ) : (
                        <Heart className="h-12 w-12 text-slate-400" />
                      )}
                    </div>
                    <div className="absolute -top-2 -right-2 w-8 h-8 bg-white rounded-full shadow-lg flex items-center justify-center">
                      <Star className="h-4 w-4 text-amber-500" />
                    </div>
                  </div>
                  
                  <h3 className="text-2xl font-semibold text-slate-800 mb-3">
                    {sidebarType === 'cart' ? 'Your Cart is Empty' : 'Your Wishlist is Empty'}
                  </h3>
                  <p className="text-slate-600 mb-8 text-lg leading-relaxed max-w-sm">
                    {sidebarType === 'cart' 
                      ? 'Discover premium publishing opportunities to elevate your brand authority' 
                      : 'Save your favorite websites for later and build your media portfolio'}
                  </p>
                  
                  <button
                    onClick={closeSidebar}
                    className="px-8 py-4 rounded-2xl font-semibold bg-slate-800 text-white hover:bg-slate-700 transition-all duration-300 shadow-lg hover:shadow-xl hover:scale-105"
                  >
                    Explore Premium Websites
                  </button>
                </motion.div>
              ) : (
                <motion.div 
                  variants={{
                    visible: {
                      transition: {
                        staggerChildren: 0.08
                      }
                    }
                  }}
                  initial="hidden"
                  animate="visible"
                  className="p-6 space-y-4"
                >
                  {items.map((item) => {
                    const authorityBadge = sidebarType === 'wishlist' ? getAuthorityBadge((item as WishlistItem).da) : null;
                    
                    return (
                      <motion.div
                        key={sidebarType === 'cart' ? (item as CartItem).id : (item as WishlistItem).websiteId}
                        variants={itemVariants}
                        className="group bg-white rounded-2xl p-5 border border-slate-200/80 hover:border-slate-300 shadow-sm hover:shadow-md transition-all duration-300"
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex-1 min-w-0">
                            {/* Website Header with Authority Badge */}
                            <div className="flex items-start justify-between mb-3">
                              <div className="flex items-center gap-3">
                                <div className="w-10 h-10 bg-linear-to-br from-blue-50 to-cyan-50 rounded-xl flex items-center justify-center border border-blue-100">
                                  <ExternalLink className="h-4 w-4 text-blue-600" />
                                </div>
                                <div className="min-w-0">
                                  <h4 className="font-semibold text-slate-800 text-lg truncate leading-tight">
                                    {item.name}
                                  </h4>
                                  <p className="text-slate-600 text-sm mt-1">{item.domain}</p>
                                </div>
                              </div>
                              
                              {authorityBadge && (
                                <div className={`px-3 py-1 rounded-full bg-linear-to-r ${authorityBadge.color} text-white text-xs font-semibold shadow-sm flex items-center gap-1`}>
                                  <Crown className="h-3 w-3" />
                                  {authorityBadge.text}
                                </div>
                              )}
                            </div>

                            {/* Stats for Wishlist Items */}
                            {sidebarType === 'wishlist' && (
                              <div className="flex items-center gap-4 mb-4 p-3 bg-slate-50 rounded-xl border border-slate-200/60">
                                <div className="text-center">
                                  <div className={`text-sm font-bold ${getDAColor((item as WishlistItem).da)}`}>
                                    DA {(item as WishlistItem).da}
                                  </div>
                                  <div className="text-xs text-slate-500 mt-1">Authority</div>
                                </div>
                                <div className="w-px h-6 bg-slate-300"></div>
                                <div className="text-center">
                                  <div className="text-sm font-bold text-orange-600">
                                    DR {(item as WishlistItem).dr}
                                  </div>
                                  <div className="text-xs text-slate-500 mt-1">Rating</div>
                                </div>
                                <div className="w-px h-6 bg-slate-300"></div>
                                <div className="text-center">
                                  <div className="text-sm font-bold text-slate-700">
                                    {(item as WishlistItem).niches[0] || 'General'}
                                  </div>
                                  <div className="text-xs text-slate-500 mt-1">Niche</div>
                                </div>
                              </div>
                            )}

                            {/* Price and Quantity Section */}
                            <div className="flex items-center justify-between pt-3 border-t border-slate-200/60">
                              <div className="flex items-center gap-4">
                                <span className="text-2xl font-bold text-slate-800">
                                  ${sidebarType === 'cart' ? (item as CartItem).price : (item as WishlistItem).price}
                                </span>
                                
                                {sidebarType === 'cart' && (
                                  <div className="flex items-center gap-1 bg-slate-100 rounded-xl border border-slate-300/60">
                                    <button
                                      onClick={() => updateQuantity((item as CartItem).id, (item as CartItem).quantity - 1)}
                                      className="p-2 hover:bg-slate-200 rounded-l-xl transition-colors text-slate-600 hover:text-slate-800"
                                      disabled={(item as CartItem).quantity <= 1}
                                    >
                                      <Minus className="h-3 w-3" />
                                    </button>
                                    <span className="px-3 font-medium text-slate-800 min-w-8 text-center text-sm">
                                      {(item as CartItem).quantity}
                                    </span>
                                    <button
                                      onClick={() => updateQuantity((item as CartItem).id, (item as CartItem).quantity + 1)}
                                      className="p-2 hover:bg-slate-200 rounded-r-xl transition-colors text-slate-600 hover:text-slate-800"
                                    >
                                      <Plus className="h-3 w-3" />
                                    </button>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>

                          {/* Action Buttons */}
                          <div className="flex flex-col gap-2 ml-4">
                            {sidebarType === 'wishlist' && (
                              <button
                                onClick={() => handleMoveToCart((item as WishlistItem).websiteId)}
                                className="p-3 bg-slate-800 text-white rounded-xl hover:bg-slate-700 transition-all duration-300 shadow-sm hover:shadow-md group"
                                title="Move to Cart"
                              >
                                <MoveRight className="h-4 w-4 group-hover:translate-x-0.5 transition-transform" />
                              </button>
                            )}
                            
                            <button
                              onClick={() =>
                                sidebarType === 'cart'
                                  ? removeItem((item as CartItem).id)
                                  : removeWishlistItem((item as WishlistItem).websiteId)
                              }
                              className="p-3 bg-rose-50 text-rose-600 rounded-xl hover:bg-rose-100 transition-all duration-300 shadow-sm hover:shadow-md group border border-rose-200/60"
                              title="Remove"
                            >
                              <Trash2 className="h-4 w-4 group-hover:scale-110 transition-transform" />
                            </button>
                          </div>
                        </div>
                      </motion.div>
                    );
                  })}
                </motion.div>
              )}
            </div>

            {/* Enhanced Footer - Only for cart - Fixed */}
            {sidebarType === 'cart' && items.length > 0 && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="border-t border-slate-200/60 p-6 space-y-6 bg-white/80 backdrop-blur-sm shrink-0"
              >
                {/* Total Price */}
                <div className="flex justify-between items-center">
                  <span className="text-slate-600 text-lg font-medium">Total Amount:</span>
                  <div className="text-right">
                    <div className="text-3xl font-bold text-slate-800">
                      ${totalPrice.toFixed(2)}
                    </div>
                    <p className="text-slate-500 text-sm">Including all applicable fees</p>
                  </div>
                </div>
                
                {/* Action Buttons */}
                <div className="flex gap-3">
                    <button
                        onClick={clearCart}
                        className="flex-1 py-3 px-4 border border-slate-300 text-slate-700 rounded-xl font-medium hover:bg-slate-50 hover:border-slate-400 transition-all duration-300 flex items-center justify-center gap-2 text-sm"
                        >
                        <Trash2 className="h-4 w-4" />
                        <span>Clear All</span>
                        </button>
                        <button
                        onClick={handleCheckout}
                        className="flex-1 bg-slate-800 text-white py-3 px-4 rounded-xl font-medium hover:bg-slate-900 transition-all duration-300 flex items-center justify-center gap-2 shadow-lg hover:shadow-xl text-sm"
                        >
                        <span>Go To Cart</span>
                        <ArrowRight className="h-4 w-4 group-hover:translate-x-0.5 transition-transform" />
                    </button>
                </div>

                {/* Security Badge */}
                <div className="flex items-center justify-center gap-2 text-slate-500 text-sm">
                  <Shield className="h-4 w-4" />
                  <span>256-bit SSL Secure • Trusted by 5,000+ Businesses</span>
                </div>
              </motion.div>
            )}

            {/* Wishlist Footer - Fixed */}
            {sidebarType === 'wishlist' && items.length > 0 && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="border-t border-slate-200/60 p-6 space-y-4 bg-white/80 backdrop-blur-sm shrink-0"
              >
                {/* Move All to Cart Button */}
                <div className="flex gap-3">
                    <button
                        onClick={handleMoveAllToCart}
                        className="flex-1 flex items-center justify-center gap-2 bg-slate-800 text-white py-3 px-4 rounded-xl font-medium hover:bg-slate-900 transition-all duration-300 shadow-md hover:shadow-lg text-sm"
                    >
                        <ShoppingBag className="h-4 w-4" />
                        <span>Move All</span>
                    </button>
                    
                    <button
                        onClick={closeSidebar}
                        className="flex-1 flex items-center justify-center gap-2 border border-slate-300 text-slate-700 py-3 px-4 rounded-xl font-medium hover:bg-slate-50 hover:border-slate-400 transition-all duration-300 text-sm"
                    >
                        <ArrowRight className="h-4 w-4" />
                        <span>Explore</span>
                    </button>
                </div>
              </motion.div>
            )}
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}