import { useState, useEffect } from 'react';
import { Header } from './components/Header';
import { Hero } from './components/Hero';
import { CategorySection } from './components/CategorySection';
import { ProductGrid } from './components/ProductGrid';
import { ProductManager } from './components/ProductManager';
import { ShoppingCart, CartItem } from './components/ShoppingCart';
import { ProductDetailModal } from './components/ProductDetailModal';
import { Footer } from './components/Footer';
import { Product } from './components/ProductCard';
import { Toaster } from './components/ui/sonner';
import { toast } from 'sonner@2.0.3';
import { loadProductsFromStorage, saveProductsToStorage, actualProducts } from './utils/productData';

// Check if admin mode is enabled via URL parameter
const isAdminMode = new URLSearchParams(window.location.search).has('admin');

// Default product data (replace with your actual products)
const defaultProducts: Product[] = [
  {
    id: '1',
    name: 'Elegant Silver Necklace',
    price: 129.99,
    originalPrice: 159.99,
    image: 'https://images.unsplash.com/photo-1676329945867-01c9975aa9d1?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjBqZXdlbHJ5JTIwbmVja2xhY2UlMjBlbGVnYW50fGVufDF8fHx8MTc1ODc2NzQ3N3ww&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Necklaces',
    isNew: true,
    isSale: true,
    rating: 4.8,
    description: 'A stunning sterling silver necklace featuring delicate chain links and a timeless pendant design.'
  },
  {
    id: '2',
    name: 'Classic Silver Ring',
    price: 89.99,
    image: 'https://images.unsplash.com/photo-1675377294835-e71bdcd9850f?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjByaW5nJTIwamV3ZWxyeSUyMGx1eHVyeXxlbnwxfHx8fDE3NTg3Njc0Nzd8MA&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Rings',
    rating: 4.6,
    description: 'Handcrafted sterling silver ring with intricate detailing and comfortable fit.'
  },
  {
    id: '3',
    name: 'Modern Silver Bracelet',
    price: 95.99,
    originalPrice: 120.99,
    image: 'https://images.unsplash.com/photo-1721206624552-d945fc1a3b8a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjBicmFjZWxldCUyMGpld2VscnklMjBtb2Rlcm58ZW58MXx8fHwxNzU4NzY3NDc3fDA&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Bracelets',
    isSale: true,
    rating: 4.7,
    description: 'Contemporary silver bracelet with adjustable chain and modern geometric design.'
  },
  {
    id: '4',
    name: 'Delicate Silver Earrings',
    price: 69.99,
    image: 'https://images.unsplash.com/photo-1758191570860-02636c34f03a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjBlYXJyaW5ncyUyMGpld2VscnklMjBlbGVnYW50fGVufDF8fHx8MTc1ODc2NzQ3OHww&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Earrings',
    isNew: true,
    rating: 4.9,
    description: 'Elegant drop earrings in sterling silver with sparkling crystal accents.'
  },
  {
    id: '5',
    name: 'Statement Silver Necklace',
    price: 179.99,
    image: 'https://images.unsplash.com/photo-1676329945867-01c9975aa9d1?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjBqZXdlbHJ5JTIwbmVja2xhY2UlMjBlbGVnYW50fGVufDF8fHx8MTc1ODc2NzQ3N3ww&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Necklaces',
    rating: 4.5,
    description: 'Bold statement piece featuring intricate silver work and artistic design elements.'
  },
  {
    id: '6',
    name: 'Vintage Silver Ring',
    price: 149.99,
    originalPrice: 199.99,
    image: 'https://images.unsplash.com/photo-1675377294835-e71bdcd9850f?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjByaW5nJTIwamV3ZWxyeSUyMGx1eHVyeXxlbnwxfHx8fDE3NTg3Njc0Nzd8MA&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Rings',
    isSale: true,
    rating: 4.8,
    description: 'Vintage-inspired sterling silver ring with ornate patterns and antique finish.'
  },
  {
    id: '7',
    name: 'Chain Silver Bracelet',
    price: 119.99,
    image: 'https://images.unsplash.com/photo-1721206624552-d945fc1a3b8a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjBicmFjZWxldCUyMGpld2VscnklMjBtb2Rlcm58ZW58MXx8fHwxNzU4NzY3NDc3fDA&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Bracelets',
    rating: 4.4,
    description: 'Classic chain bracelet in sterling silver with secure clasp and polished finish.'
  },
  {
    id: '8',
    name: 'Stud Silver Earrings',
    price: 45.99,
    image: 'https://images.unsplash.com/photo-1758191570860-02636c34f03a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzaWx2ZXIlMjBlYXJyaW5ncyUyMGpld2VscnklMjBlbGVnYW50fGVufDF8fHx8MTc1ODc2NzQ3OHww&ixlib=rb-4.1.0&q=80&w=1080',
    category: 'Earrings',
    isNew: true,
    rating: 4.7,
    description: 'Simple yet elegant sterling silver stud earrings perfect for everyday wear.'
  }
];

export default function App() {
  const [products, setProducts] = useState<Product[]>([]);
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [isProductModalOpen, setIsProductModalOpen] = useState(false);

  // Load products on component mount
  useEffect(() => {
    const loadedProducts = loadProductsFromStorage();
    setProducts(loadedProducts);
  }, []);

  // Save products when they change
  const handleProductsChange = (newProducts: Product[]) => {
    setProducts(newProducts);
    saveProductsToStorage(newProducts);
  };

  const addToCart = (product: Product, quantity: number = 1) => {
    setCartItems(prevItems => {
      const existingItem = prevItems.find(item => item.id === product.id);
      
      if (existingItem) {
        return prevItems.map(item =>
          item.id === product.id
            ? { ...item, quantity: item.quantity + quantity }
            : item
        );
      } else {
        return [...prevItems, { ...product, quantity }];
      }
    });
    
    toast.success(`${product.name} added to cart!`);
  };

  const updateCartQuantity = (productId: string, quantity: number) => {
    if (quantity === 0) {
      removeFromCart(productId);
      return;
    }
    
    setCartItems(prevItems =>
      prevItems.map(item =>
        item.id === productId ? { ...item, quantity } : item
      )
    );
  };

  const removeFromCart = (productId: string) => {
    setCartItems(prevItems => prevItems.filter(item => item.id !== productId));
    toast.success('Item removed from cart');
  };

  const openProductModal = (product: Product) => {
    setSelectedProduct(product);
    setIsProductModalOpen(true);
  };

  const closeProductModal = () => {
    setSelectedProduct(null);
    setIsProductModalOpen(false);
  };

  const handleCategorySelect = (category: string) => {
    toast.info(`Browsing ${category} collection`);
    // In a real app, this would filter products or navigate to category page
  };

  const cartItemCount = cartItems.reduce((total, item) => total + item.quantity, 0);

  return (
    <div className="min-h-screen bg-background">
      <Header cartItemCount={cartItemCount} onCartClick={() => setIsCartOpen(true)} />
      
      <main>
        {isAdminMode ? (
          <div className="container mx-auto px-4 py-8">
            <ProductManager
              products={products}
              onProductsChange={handleProductsChange}
              isAdminMode={isAdminMode}
            />
          </div>
        ) : (
          <>
            <Hero />
            <CategorySection onCategorySelect={handleCategorySelect} />
            <ProductGrid
              products={products}
              onAddToCart={addToCart}
              onProductClick={openProductModal}
              title="Featured Collection"
            />
          </>
        )}
      </main>

      <Footer />

      {/* Shopping Cart */}
      <ShoppingCart
        isOpen={isCartOpen}
        onClose={() => setIsCartOpen(false)}
        cartItems={cartItems}
        onUpdateQuantity={updateCartQuantity}
        onRemoveItem={removeFromCart}
      />

      {/* Product Detail Modal */}
      <ProductDetailModal
        product={selectedProduct}
        isOpen={isProductModalOpen}
        onClose={closeProductModal}
        onAddToCart={addToCart}
      />

      {/* Toast Notifications */}
      <Toaster />
    </div>
  );
}