import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import api from '../api'
import ProductCard from '../components/ProductCard'
import CategoryCard from '../components/CategoryCard'
import '../styles/global.css'

export default function Home() {
  const [featured, setFeatured] = useState([])
  const [newArrivals, setNewArrivals] = useState([])
  const [onSale, setOnSale] = useState([])
  const [categories, setCategories] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    try {
      const [featuredRes, newRes, saleRes, catRes] = await Promise.all([
        api.get('/products?featured=true&limit=8'),
        api.get('/products?limit=8'),
        api.get('/products?on_sale=true&limit=8'),
        api.get('/categories'),
      ])

      setFeatured(featuredRes?.data || [])
      setNewArrivals(newRes?.data || [])
      setOnSale(saleRes?.data || [])
      setCategories(catRes?.data || [])
    } catch (error) {
      console.error('Error fetching data:', error)
      // Set empty arrays on error to prevent crashes
      setFeatured([])
      setNewArrivals([])
      setOnSale([])
      setCategories([])
    } finally {
      setLoading(false)
    }
  }

  if (loading) return <div className="loading">Loading...</div>

  const brands = Array.from(
    new Set([...featured, ...newArrivals, ...onSale].map((item) => item.brand).filter(Boolean))
  ).slice(0, 8)

  return (
    <div className="home">
      <section className="hero">
        <div className="hero-content">
          <span className="kicker">Luxury Sneaker House</span>
          <h1>Curated Premium Sneakers. Built for Statement.</h1>
          <p>
            Discover exclusive releases, iconic silhouettes, and elevated essentials in a modern black-and-gold retail experience.
          </p>
          <div className="hero-cta-row">
            <Link to="/products" className="btn btn-large">Shop Now</Link>
            <Link to="/sales" className="btn btn-secondary btn-large">Explore Sales</Link>
          </div>
        </div>
        <div className="hero-media">
          <img
            src="https://images.unsplash.com/photo-1543508282-6319a3e2621f?auto=format&fit=crop&w=1400&q=80"
            alt="Luxury sneaker collection"
          />
        </div>
      </section>

      <section className="feature-strip">
        <div className="item">
          <strong>100% Authentic</strong>
          <span>Verified premium stock</span>
        </div>
        <div className="item">
          <strong>Secure Payment</strong>
          <span>Safe and encrypted checkout</span>
        </div>
        <div className="item">
          <strong>Free Shipping</strong>
          <span>Orders over ₪299</span>
        </div>
        <div className="item">
          <strong>Easy Returns</strong>
          <span>14-day return policy</span>
        </div>
      </section>

      <section className="section">
        <div className="section-header">
          <h2>Featured Products</h2>
          <p>Hand-picked from this week's premium drops</p>
        </div>
        <div className="grid">
          {featured.map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </section>

      <section className="section">
        <div className="section-header">
          <h2>New Arrivals</h2>
          <p>Fresh releases from top designer brands</p>
        </div>
        <div className="grid">
          {newArrivals.slice(0, 8).map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </section>

      <section className="section sale-banner">
        <h2>Private Sale Collection</h2>
        <p>Limited-time markdowns across selected statement pieces.</p>
        <Link to="/sales" className="btn btn-large">View All Sales</Link>
      </section>

      <section className="section">
        <div className="section-header">
          <h2>Best Sellers</h2>
          <p>The silhouettes our community keeps coming back for</p>
        </div>
        <div className="grid">
          {onSale.slice(0, 8).map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </section>

      <section className="section">
        <div className="section-header">
          <h2>Shop by Category</h2>
          <p>Build your fit by category</p>
        </div>
        <div className="grid">
          {categories.map((cat) => (
            <CategoryCard key={cat.id} category={cat} />
          ))}
        </div>
      </section>

      {brands.length > 0 && (
        <section className="section">
          <div className="section-header">
            <h2>Brands</h2>
            <p>Curated premium houses</p>
          </div>
          <div className="grid">
            {brands.map((brand) => (
              <div key={brand} className="category-card">
                <div style={{ padding: '1.2rem' }}>
                  <h3>{brand}</h3>
                  <p>Explore selected {brand} silhouettes in the Brand Master collection.</p>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      <section className="promo-banner">
        <h3>Join the Private Client List</h3>
        <p>Get priority access to drops, restocks, and members-only pricing.</p>
        <input type="email" placeholder="Enter your email" />
        <button className="btn">Subscribe</button>
      </section>
    </div>
  )
}
