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

export default function Products() {
  const [searchParams] = useSearchParams()
  const [products, setProducts] = useState([])
  const [loading, setLoading] = useState(true)
  const [sortBy, setSortBy] = useState('latest')
  const [activeFilters, setActiveFilters] = useState({})

  useEffect(() => {
    fetchProducts()
  }, [searchParams, activeFilters, sortBy])

  const fetchProducts = async () => {
    try {
      setLoading(true)
      const categorySlug = searchParams.get('category')
      const params = { limit: 50, ...activeFilters }

      if (categorySlug) {
        // Get category by slug
        const catRes = await api.get('/categories')
        const category = catRes.data.find((c) => c.slug === categorySlug)
        if (category) params.category_id = category.id
      }

      // Convert filter values to API parameters
      if (activeFilters.min_price) params.min_price = parseFloat(activeFilters.min_price)
      if (activeFilters.max_price) params.max_price = parseFloat(activeFilters.max_price)
      if (activeFilters.onSale) params.on_sale = true
      if (activeFilters.model_id) params.model_id = parseInt(activeFilters.model_id)

      const response = await api.get('/products', { params })
      let sorted = [...response.data]

      // Apply client-side sorting
      if (sortBy === 'price-low') {
        sorted.sort((a, b) => (a.discount_price || a.price) - (b.discount_price || b.price))
      } else if (sortBy === 'price-high') {
        sorted.sort((a, b) => (b.discount_price || b.price) - (a.discount_price || a.price))
      } else if (sortBy === 'name') {
        sorted.sort((a, b) => a.name.localeCompare(b.name))
      }

      setProducts(sorted)
    } catch (error) {
      console.error('Error fetching products:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleFilter = (filters) => {
    setActiveFilters(filters)
  }

  return (
    <div className="products-page">
      <h1>Our Products</h1>

      <div className="products-container">
        <ProductFilters onFilter={handleFilter} />

        <div className="products-content">
          <div className="sort-bar">
            <label>Sort by:</label>
            <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
              <option value="latest">Latest</option>
              <option value="price-low">Price: Low to High</option>
              <option value="price-high">Price: High to Low</option>
              <option value="name">Name: A to Z</option>
            </select>
            <span className="product-count">{products.length} products</span>
          </div>

          {loading ? (
            <div className="loading">Loading products...</div>
          ) : products.length > 0 ? (
            <div className="grid">
              {products.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
            </div>
          ) : (
            <div className="no-products">
              <p>No products found.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
