'use client';

import React, { useState, useEffect } from 'react';
import { LucideShoppingCart, LucideSearch, LucideFilter } from 'lucide-react';
import * as Dialog from '@radix-ui/react-dialog';

interface Product {
  id: number;
  name: string;
  price: number;
  image: string;
  category: string;
  size: string;
  color: string;
}

const SwagStorefront: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [filters, setFilters] = useState({
    category: '',
    size: '',
    color: '',
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch products on component mount
  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const data = await fetch('/api/swag/products').then(r => r.json());
        setProducts(data.products || []);
        setFilteredProducts(data.products || []);
        setLoading(false);
      } catch (err) {
        setError('Failed to load products.');
        setLoading(false);
      }
    };

    fetchProducts();
  }, []);

  // Handle search
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const query = e.target.value;
    setSearchQuery(query);

    const filtered = products.filter((product) =>
      product.name.toLowerCase().includes(query.toLowerCase())
    );
    setFilteredProducts(filtered);
  };

  // Handle filter changes
  const handleFilterChange = (key: string, value: string) => {
    const newFilters = { ...filters, [key]: value };
    setFilters(newFilters);

    const filtered = products.filter((product) => {
      return (
        (newFilters.category ? product.category === newFilters.category : true) &&
        (newFilters.size ? product.size === newFilters.size : true) &&
        (newFilters.color ? product.color === newFilters.color : true)
      );
    });

    setFilteredProducts(filtered);
  };

  // Add to cart functionality
  const handleAddToCart = async (productId: number) => {
    try {
      await fetch('/api/swag/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId }) });
      alert('Product added to cart!');
    } catch (err) {
      alert('Failed to add product to cart.');
    }
  };

  if (loading) {
    return <div className="text-center text-white">Loading...</div>;
  }

  if (error) {
    return <div className="text-center text-red-500">{error}</div>;
  }

  return (
    <div className="bg-brand-bg text-white min-h-screen p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <header className="flex items-center justify-between mb-6">
          <h1 className="text-3xl font-bold text-brand">Swag Storefront</h1>
          <div className="flex items-center space-x-4">
            <div className="relative">
              <LucideSearch className="absolute left-3 top-2.5 text-gray-400" size={20} />
              <input
                type="text"
                placeholder="Search products..."
                value={searchQuery}
                onChange={handleSearch}
                className="pl-10 pr-4 py-2 bg-white/5 text-white border border-white/10 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand transition"
              />
            </div>
            <Dialog.Root>
              <Dialog.Trigger asChild>
                <button className="bg-brand-secondary-light text-white px-4 py-2 rounded-lg hover:bg-brand-secondary transition">
                  <LucideFilter className="inline-block mr-2" size={20} />
                  Filters
                </button>
              </Dialog.Trigger>
              <Dialog.Portal>
                <Dialog.Overlay className="fixed inset-0 bg-black/50" />
                <Dialog.Content className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-brand-bg p-6 rounded-xl border border-white/10 shadow-lg">
                  <h2 className="text-xl font-bold text-brand mb-4">Filters</h2>
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Category</label>
                      <select
                        value={filters.category}
                        onChange={(e) => handleFilterChange('category', e.target.value)}
                        className="w-full bg-white/5 text-white border border-white/10 rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-brand transition"
                      >
                        <option value="">All</option>
                        <option value="t-shirts">T-Shirts</option>
                        <option value="hoodies">Hoodies</option>
                        <option value="accessories">Accessories</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Size</label>
                      <select
                        value={filters.size}
                        onChange={(e) => handleFilterChange('size', e.target.value)}
                        className="w-full bg-white/5 text-white border border-white/10 rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-brand transition"
                      >
                        <option value="">All</option>
                        <option value="s">Small</option>
                        <option value="m">Medium</option>
                        <option value="l">Large</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Color</label>
                      <select
                        value={filters.color}
                        onChange={(e) => handleFilterChange('color', e.target.value)}
                        className="w-full bg-white/5 text-white border border-white/10 rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-brand transition"
                      >
                        <option value="">All</option>
                        <option value="black">Black</option>
                        <option value="white">White</option>
                        <option value="blue">Blue</option>
                      </select>
                    </div>
                  </div>
                  <Dialog.Close asChild>
                    <button className="mt-4 bg-brand text-white px-4 py-2 rounded-lg hover:bg-brand-deep transition">
                      Apply Filters
                    </button>
                  </Dialog.Close>
                </Dialog.Content>
              </Dialog.Portal>
            </Dialog.Root>
          </div>
        </header>

        {/* Product Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {filteredProducts.map((product) => (
            <div
              key={product.id}
              className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-xl p-4 flex flex-col items-center text-center"
            >
              <img
                src={product.image}
                alt={product.name}
                className="w-full h-40 object-cover rounded-lg mb-4"
              />
              <h3 className="text-lg font-bold text-brand">{product.name}</h3>
              <p className="text-gray-400">${product.price.toFixed(2)}</p>
              <button
                onClick={() => handleAddToCart(product.id)}
                className="mt-4 bg-brand-secondary-light text-white px-4 py-2 rounded-lg hover:bg-brand-secondary transition"
              >
                <LucideShoppingCart className="inline-block mr-2" size={20} />
                Add to Cart
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default SwagStorefront;