import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { getProducts } from '../utils/api';

const ShopPage = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [category, setCategory] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    loadProducts();
  }, [category]);

  const loadProducts = async () => {
    try {
      const categoryParam = category === 'all' ? null : category;
      const response = await getProducts(categoryParam);
      setProducts(response.data);
    } catch (error) {
      console.error('Error loading products:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredProducts = products.filter(product =>
    product.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const featuredProducts = products.filter(p => p.featured);

  const formatPrice = (price) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      minimumFractionDigits: 0
    }).format(price);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-5 py-4 flex justify-between items-center">
          <Link to="/" className="flex items-center gap-3">
            <img src="/assets/img/logo1.png" alt="Logo" className="h-12" />
            <div>
              <div className="text-xl font-bold text-gray-900">
                <strong className="text-blue-600">RH</strong> Elektronik
              </div>
              <small className="text-xs text-gray-500 uppercase tracking-wide">Toko Online</small>
            </div>
          </Link>

          <div className="flex gap-4">
            <Link to="/" className="text-gray-700 font-semibold hover:text-blue-600">Home</Link>
            <Link to="/blog" className="text-gray-700 font-semibold hover:text-blue-600">Blog</Link>
            <Link to="/shop" className="text-blue-600 font-semibold">Shop</Link>
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <section className="bg-gradient-to-br from-blue-600 to-blue-800 text-white py-16">
        <div className="max-w-7xl mx-auto px-5 text-center">
          <h1 className="text-5xl font-extrabold mb-4">🛍️ Toko Online</h1>
          <p className="text-xl opacity-90 mb-6">Spareparts & Aksesoris Elektronik Berkualitas</p>
          
          {/* Search Bar */}
          <div className="max-w-2xl mx-auto">
            <input
              type="text"
              placeholder="🔍 Cari produk..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-6 py-4 rounded-xl text-gray-900 text-lg focus:outline-none focus:ring-4 focus:ring-blue-300"
            />
          </div>
        </div>
      </section>

      <div className="max-w-7xl mx-auto px-5 py-12">
        {/* Categories */}
        <div className="flex gap-3 mb-8 flex-wrap">
          <button
            onClick={() => setCategory('all')}
            className={`px-6 py-3 rounded-xl font-bold transition ${
              category === 'all'
                ? 'bg-blue-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            📦 Semua Produk
          </button>
          <button
            onClick={() => setCategory('Spareparts')}
            className={`px-6 py-3 rounded-xl font-bold transition ${
              category === 'Spareparts'
                ? 'bg-blue-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            🔧 Spareparts
          </button>
          <button
            onClick={() => setCategory('Aksesoris')}
            className={`px-6 py-3 rounded-xl font-bold transition ${
              category === 'Aksesoris'
                ? 'bg-blue-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            ✨ Aksesoris
          </button>
          <button
            onClick={() => setCategory('Elektronik')}
            className={`px-6 py-3 rounded-xl font-bold transition ${
              category === 'Elektronik'
                ? 'bg-blue-600 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100'
            }`}
          >
            📱 Elektronik
          </button>
        </div>

        {/* Featured Products */}
        {featuredProducts.length > 0 && (
          <div className="mb-12">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">⭐ Produk Unggulan</h2>
            <div className="grid md:grid-cols-4 gap-6">
              {featuredProducts.map((product) => (
                <ProductCard key={product.id} product={product} formatPrice={formatPrice} />
              ))}
            </div>
          </div>
        )}

        {/* All Products */}
        <div>
          <h2 className="text-2xl font-bold text-gray-900 mb-6">
            {category === 'all' ? '📦 Semua Produk' : `📦 ${category}`}
            <span className="text-gray-500 text-lg ml-3">({filteredProducts.length} produk)</span>
          </h2>

          {loading ? (
            <div className="text-center py-20">
              <div className="text-xl text-gray-600">Loading...</div>
            </div>
          ) : filteredProducts.length === 0 ? (
            <div className="text-center py-20">
              <p className="text-xl text-gray-500">Tidak ada produk ditemukan</p>
            </div>
          ) : (
            <div className="grid md:grid-cols-4 gap-6">
              {filteredProducts.map((product) => (
                <ProductCard key={product.id} product={product} formatPrice={formatPrice} />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Footer */}
      <footer className="bg-gray-900 text-gray-400 text-center py-10 mt-20">
        <p>© 2026 CV RH Elektronik - Authorized Service Center</p>
      </footer>
    </div>
  );
};

const ProductCard = ({ product, formatPrice }) => {
  const hasDiscount = product.original_price > product.price;
  const discount = hasDiscount
    ? Math.round(((product.original_price - product.price) / product.original_price) * 100)
    : 0;

  return (
    <Link
      to={`/product/${product.id}`}
      className="bg-white rounded-2xl overflow-hidden shadow-md hover:shadow-2xl transition-all duration-300 hover:-translate-y-2"
    >
      {/* Image */}
      <div className="relative h-56 bg-gray-100">
        {product.images && product.images[0] ? (
          <img
            src={product.images[0]}
            alt={product.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center text-gray-400 text-5xl">
            📦
          </div>
        )}
        {hasDiscount && (
          <div className="absolute top-3 right-3 bg-red-500 text-white px-3 py-1 rounded-full font-bold text-sm">
            -{discount}%
          </div>
        )}
        {!product.is_available && (
          <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
            <span className="bg-red-600 text-white px-4 py-2 rounded-lg font-bold">Stok Habis</span>
          </div>
        )}
      </div>

      {/* Content */}
      <div className="p-5">
        <h3 className="font-bold text-lg text-gray-900 mb-2 line-clamp-2">{product.name}</h3>
        
        {/* Price */}
        <div className="mb-3">
          {hasDiscount && (
            <p className="text-sm text-gray-400 line-through">{formatPrice(product.original_price)}</p>
          )}
          <p className="text-2xl font-extrabold text-blue-600">{formatPrice(product.price)}</p>
        </div>

        {/* Stock & Category */}
        <div className="flex items-center justify-between text-sm text-gray-500 mb-3">
          <span>📦 Stok: {product.stock}</span>
          <span className="bg-gray-100 px-2 py-1 rounded">{product.category}</span>
        </div>

        {/* Button */}
        <button className="w-full bg-blue-600 text-white py-3 rounded-xl font-bold hover:bg-blue-700 transition">
          Lihat Detail
        </button>
      </div>
    </Link>
  );
};

export default ShopPage;