import React, { useState, useEffect } from 'react'
import api from '../api'
import ProductCard from '../components/ProductCard'
import '../styles/global.css'

export default function Sales() {
  const [products, setProducts] = useState([])
  const [loading, setLoading] = useState(true)

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

  const fetchSaleProducts = async () => {
    try {
      const response = await api.get('/products', {
        params: {
          on_sale: true,
          limit: 50,
        },
      })
      setProducts(response.data)
    } catch (error) {
      console.error('Error fetching sale products:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="sales-page">
      <div className="sales-header">
        <h1>🔥 Limited Time Offers</h1>
        <p>Huge discounts on selected items - Limited time only!</p>
      </div>

      {loading ? (
        <div className="loading">Loading...</div>
      ) : products.length > 0 ? (
        <div className="sales-container">
          <div className="grid">
            {products.map((product) => (
              <div key={product.id} className="sale-product">
                <ProductCard product={product} />
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="no-products">
          <p>No products on sale at the moment.</p>
        </div>
      )}
    </div>
  )
}
