'use client';

import React, { useState, useEffect } from 'react';
import { ShoppingCart, Search, Filter, Plus, Minus, X, Package, BarChart3, Users, Tag } from 'lucide-react';
import * as Dialog from '@radix-ui/react-dialog';
import * as Tabs from '@radix-ui/react-tabs';
import AdminDashboard from './admin-dashboard';
import CheckoutFlow from './checkout-flow';
import { BRAND } from '@/lib/white-label/constants';

interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  category: string;
  sizes: string[];
  colors: string[];
  stock: number;
  image: string;
}

interface CartItem extends Product {
  quantity: number;
  selectedSize: string;
  selectedColor: string;
}

// Sample products data (in production, this would come from the API)
const SAMPLE_PRODUCTS: Product[] = [
  {
    id: '1',
    name: 'GFS Classic Hoodie',
    description: `Premium cotton blend hoodie with embroidered ${BRAND.companyName} logo`,
    price: 79.99,
    category: 'hoodies',
    sizes: ['S', 'M', 'L', 'XL', '2XL'],
    colors: ['Black', 'Navy', 'Gray'],
    stock: 50,
    image: 'https://png.pngtree.com/png-vector/20230618/ourmid/pngtree-long-sleeve-hoodie-vector-illustration-template-png-image_7143768.png'
  },
  {
    id: '2',
    name: 'Familiars Tech Tee',
    description: 'Lightweight performance t-shirt with reflective logo',
    price: 34.99,
    category: 't-shirts',
    sizes: ['XS', 'S', 'M', 'L', 'XL'],
    colors: ['Black', 'White', 'Cyan'],
    stock: 100,
    image: 'https://cdn.shopify.com/s/files/1/0070/7032/files/shirteecloud.png?v=1726987018'
  },
  {
    id: '3',
    name: 'Ghost Operator Cap',
    description: 'Snapback cap with embroidered ghost icon',
    price: 29.99,
    category: 'hats',
    sizes: ['One Size'],
    colors: ['Black', 'Navy'],
    stock: 75,
    image: 'https://placehold.co/1200x600/e2e8f0/1e293b?text=image_of_a_black_or_navy_cap_hat__one_size'
  },
  {
    id: '4',
    name: 'Executive Dress Shirt',
    description: 'Premium button-down with subtle FF monogram',
    price: 89.99,
    category: 'shirts',
    sizes: ['S', 'M', 'L', 'XL'],
    colors: ['White', 'Light Blue', 'Black'],
    stock: 30,
    image: 'https://img.freepik.com/free-vector/basic-t-shirt-outline-glyph_78370-6763.jpg?semt=ais_hybrid&w=740&q=80'
  },
  {
    id: '5',
    name: 'Familiars Winter Coat',
    description: 'Insulated jacket with waterproof shell and FF branding',
    price: 199.99,
    category: 'coats',
    sizes: ['S', 'M', 'L', 'XL', '2XL'],
    colors: ['Black', 'Charcoal'],
    stock: 20,
    image: 'https://images.pexels.com/photos/14925243/pexels-photo-14925243.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'
  },
  {
    id: '6',
    name: 'Developer Beanie',
    description: 'Knit beanie with embroidered code brackets',
    price: 24.99,
    category: 'hats',
    sizes: ['One Size'],
    colors: ['Black', 'Gray', 'Cyan'],
    stock: 60,
    image: 'http://sublimationblankscompany.com/cdn/shop/files/beaniehatscolors.jpg?v=1692481108'
  },
];

const CATEGORIES = ['all', 'hoodies', 't-shirts', 'shirts', 'hats', 'coats'];

const MainComponent: React.FC = () => {
  const [products, setProducts] = useState<Product[]>(SAMPLE_PRODUCTS);
  const [cart, setCart] = useState<CartItem[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [cartOpen, setCartOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [selectedSize, setSelectedSize] = useState('');
  const [selectedColor, setSelectedColor] = useState('');

  // Filter products
  const filteredProducts = products.filter(product => {
    const matchesSearch = product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         product.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || product.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  // Cart functions
  const addToCart = (product: Product) => {
    if (!selectedSize || !selectedColor) {
      alert('Please select size and color');
      return;
    }
    
    const existingItem = cart.find(
      item => item.id === product.id && item.selectedSize === selectedSize && item.selectedColor === selectedColor
    );

    if (existingItem) {
      setCart(cart.map(item =>
        item.id === product.id && item.selectedSize === selectedSize && item.selectedColor === selectedColor
          ? { ...item, quantity: item.quantity + 1 }
          : item
      ));
    } else {
      setCart([...cart, { ...product, quantity: 1, selectedSize, selectedColor }]);
    }
    setSelectedProduct(null);
    setSelectedSize('');
    setSelectedColor('');
  };

  const removeFromCart = (itemId: string, size: string, color: string) => {
    setCart(cart.filter(item => !(item.id === itemId && item.selectedSize === size && item.selectedColor === color)));
  };

  const updateQuantity = (itemId: string, size: string, color: string, delta: number) => {
    setCart(cart.map(item => {
      if (item.id === itemId && item.selectedSize === size && item.selectedColor === color) {
        const newQty = item.quantity + delta;
        return newQty > 0 ? { ...item, quantity: newQty } : item;
      }
      return item;
    }).filter(item => item.quantity > 0));
  };

  const cartTotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const cartCount = cart.reduce((sum, item) => sum + item.quantity, 0);

  return (
    <Tabs.Root defaultValue="store" className="w-full">
      <Tabs.List className="flex gap-1 mb-6 p-1 bg-white/5 rounded-lg w-fit">
        <Tabs.Trigger
          value="store"
          className="px-4 py-2 text-sm font-medium rounded-md transition-colors data-[state=active]:bg-brand-deep data-[state=active]:text-white text-gray-400 hover:text-white"
        >
          <Package className="w-4 h-4 inline mr-2" />
          Store
        </Tabs.Trigger>
        <Tabs.Trigger
          value="admin"
          className="px-4 py-2 text-sm font-medium rounded-md transition-colors data-[state=active]:bg-brand-deep data-[state=active]:text-white text-gray-400 hover:text-white"
        >
          <BarChart3 className="w-4 h-4 inline mr-2" />
          Admin Dashboard
        </Tabs.Trigger>
      </Tabs.List>

      <Tabs.Content value="store">
        {/* Store Header */}
        <div className="flex flex-col md:flex-row gap-4 mb-6">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search products..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep"
            />
          </div>
          <div className="flex gap-2 flex-wrap">
            {CATEGORIES.map(cat => (
              <button
                key={cat}
                onClick={() => setSelectedCategory(cat)}
                className={`px-4 py-2 rounded-lg capitalize transition-colors ${
                  selectedCategory === cat
                    ? 'bg-brand-deep text-white'
                    : 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-white'
                }`}
              >
                {cat}
              </button>
            ))}
          </div>
          <button
            onClick={() => setCartOpen(true)}
            className="relative px-4 py-2 bg-brand-deep text-white rounded-lg hover:bg-brand-deep transition-colors flex items-center gap-2"
          >
            <ShoppingCart className="w-5 h-5" />
            Cart
            {cartCount > 0 && (
              <span className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 rounded-full text-xs flex items-center justify-center">
                {cartCount}
              </span>
            )}
          </button>
        </div>

        {/* Product Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredProducts.map(product => (
            <div
              key={product.id}
              className="glass-card p-4 rounded-xl hover:border-brand-deep/50 transition-colors cursor-pointer"
              onClick={() => {
                setSelectedProduct(product);
                setSelectedSize(product.sizes[0]);
                setSelectedColor(product.colors[0]);
              }}
            >
              <div className="aspect-square bg-white/5 rounded-lg mb-4 flex items-center justify-center">
                <Package className="w-16 h-16 text-gray-600" />
              </div>
              <h3 className="text-lg font-semibold text-white mb-1">{product.name}</h3>
              <p className="text-gray-400 text-sm mb-2 line-clamp-2">{product.description}</p>
              <div className="flex justify-between items-center">
                <span className="text-brand font-bold text-xl">${product.price.toFixed(2)}</span>
                <span className={`text-sm ${product.stock > 10 ? 'text-green-400' : 'text-orange-400'}`}>
                  {product.stock} in stock
                </span>
              </div>
            </div>
          ))}
        </div>

        {filteredProducts.length === 0 && (
          <div className="text-center py-12 text-gray-400">
            <Package className="w-16 h-16 mx-auto mb-4 opacity-50" />
            <p>No products found matching your criteria</p>
          </div>
        )}

        {/* Product Detail Dialog */}
        <Dialog.Root open={!!selectedProduct} onOpenChange={() => setSelectedProduct(null)}>
          <Dialog.Portal>
            <Dialog.Overlay className="fixed inset-0 bg-black/80 z-50" />
            <Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-brand-bg border border-white/10 rounded-xl p-6 w-full max-w-md z-50">
              {selectedProduct && (
                <>
                  <Dialog.Title className="text-xl font-bold text-white mb-2">
                    {selectedProduct.name}
                  </Dialog.Title>
                  <p className="text-gray-400 mb-4">{selectedProduct.description}</p>
                  <p className="text-2xl font-bold text-brand mb-4">${selectedProduct.price.toFixed(2)}</p>
                  
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm text-gray-400 mb-2">Size</label>
                      <div className="flex gap-2 flex-wrap">
                        {selectedProduct.sizes.map(size => (
                          <button
                            key={size}
                            onClick={() => setSelectedSize(size)}
                            className={`px-3 py-1 rounded border transition-colors ${
                              selectedSize === size
                                ? 'border-brand-deep bg-brand-deep/20 text-brand'
                                : 'border-white/20 text-gray-400 hover:border-white/40'
                            }`}
                          >
                            {size}
                          </button>
                        ))}
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm text-gray-400 mb-2">Color</label>
                      <div className="flex gap-2 flex-wrap">
                        {selectedProduct.colors.map(color => (
                          <button
                            key={color}
                            onClick={() => setSelectedColor(color)}
                            className={`px-3 py-1 rounded border transition-colors ${
                              selectedColor === color
                                ? 'border-brand-deep bg-brand-deep/20 text-brand'
                                : 'border-white/20 text-gray-400 hover:border-white/40'
                            }`}
                          >
                            {color}
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>
                  
                  <button
                    onClick={() => addToCart(selectedProduct)}
                    className="w-full mt-6 py-3 bg-brand-deep text-white rounded-lg hover:bg-brand-deep transition-colors font-medium"
                  >
                    Add to Cart
                  </button>
                  
                  <Dialog.Close asChild>
                    <button className="absolute top-4 right-4 text-gray-400 hover:text-white">
                      <X className="w-5 h-5" />
                    </button>
                  </Dialog.Close>
                </>
              )}
            </Dialog.Content>
          </Dialog.Portal>
        </Dialog.Root>

        {/* Cart Dialog */}
        <Dialog.Root open={cartOpen} onOpenChange={setCartOpen}>
          <Dialog.Portal>
            <Dialog.Overlay className="fixed inset-0 bg-black/80 z-50" />
            <Dialog.Content className="fixed top-0 right-0 h-full w-full max-w-md bg-brand-bg border-l border-white/10 p-6 z-50 overflow-y-auto">
              <Dialog.Title className="text-xl font-bold text-white mb-4 flex items-center gap-2">
                <ShoppingCart className="w-5 h-5" />
                Your Cart ({cartCount} items)
              </Dialog.Title>
              
              {cart.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                  <ShoppingCart className="w-16 h-16 mx-auto mb-4 opacity-50" />
                  <p>Your cart is empty</p>
                </div>
              ) : (
                <>
                  <div className="space-y-4 mb-6">
                    {cart.map((item) => (
                      <div key={`${item.id}-${item.selectedSize}-${item.selectedColor}`} className="flex gap-4 p-4 bg-white/5 rounded-lg">
                        <div className="w-16 h-16 bg-white/10 rounded flex items-center justify-center">
                          <Package className="w-8 h-8 text-gray-600" />
                        </div>
                        <div className="flex-1">
                          <h4 className="text-white font-medium">{item.name}</h4>
                          <p className="text-sm text-gray-400">{item.selectedSize} / {item.selectedColor}</p>
                          <p className="text-brand">${item.price.toFixed(2)}</p>
                        </div>
                        <div className="flex flex-col items-end gap-2">
                          <button
                            onClick={() => removeFromCart(item.id, item.selectedSize, item.selectedColor)}
                            className="text-red-400 hover:text-red-300"
                          >
                            <X className="w-4 h-4" />
                          </button>
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => updateQuantity(item.id, item.selectedSize, item.selectedColor, -1)}
                              className="w-6 h-6 rounded bg-white/10 flex items-center justify-center hover:bg-white/20"
                            >
                              <Minus className="w-3 h-3" />
                            </button>
                            <span className="text-white w-6 text-center">{item.quantity}</span>
                            <button
                              onClick={() => updateQuantity(item.id, item.selectedSize, item.selectedColor, 1)}
                              className="w-6 h-6 rounded bg-white/10 flex items-center justify-center hover:bg-white/20"
                            >
                              <Plus className="w-3 h-3" />
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                  
                  <div className="border-t border-white/10 pt-4">
                    <div className="flex justify-between text-lg mb-4">
                      <span className="text-gray-400">Total</span>
                      <span className="text-white font-bold">${cartTotal.toFixed(2)}</span>
                    </div>
                    <button className="w-full py-3 bg-brand-deep text-white rounded-lg hover:bg-brand-deep transition-colors font-medium">
                      Proceed to Checkout
                    </button>
                  </div>
                </>
              )}
              
              <Dialog.Close asChild>
                <button className="absolute top-4 right-4 text-gray-400 hover:text-white">
                  <X className="w-5 h-5" />
                </button>
              </Dialog.Close>
            </Dialog.Content>
          </Dialog.Portal>
        </Dialog.Root>
      </Tabs.Content>

      <Tabs.Content value="admin">
        <AdminDashboard />
      </Tabs.Content>
    </Tabs.Root>
  );
};

export default MainComponent;
