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'

const PAGE_SIZE = 24

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({})
  const [currentPage, setCurrentPage] = useState(1)
  const [totalCount, setTotalCount] = useState(0)
  const [showAll, setShowAll] = useState(false)

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

  const buildFilterParams = () => {
    const params = {}

    const categorySlug = searchParams.get('category')
    // category_id resolved later via async call; passed in fetchProducts

    if (activeFilters.gender && activeFilters.gender !== '') params.gender = activeFilters.gender
    if (activeFilters.brand && activeFilters.brand !== '') params.brand = activeFilters.brand
    if (activeFilters.model_id && activeFilters.model_id !== '') params.model_id = parseInt(activeFilters.model_id)
    if (activeFilters.min_price && activeFilters.min_price !== '') params.min_price = parseFloat(activeFilters.min_price)
    if (activeFilters.max_price && activeFilters.max_price !== '') params.max_price = parseFloat(activeFilters.max_price)
    if (activeFilters.onSale === true) params.on_sale = true

    if (sortBy === 'price-low') params.sort_by = 'price_asc'
    else if (sortBy === 'price-high') params.sort_by = 'price_desc'
    else if (sortBy === 'name') params.sort_by = 'name'
    else if (sortBy === 'brand') params.sort_by = 'brand'
    else if (sortBy === 'popular') params.sort_by = 'popular'

    return params
  }

  const fetchProducts = async () => {
    try {
      setLoading(true)
      const params = buildFilterParams()

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

      // Fetch total count for pagination
      const countRes = await api.get('/products/count', { params })
      const total = countRes.data.count
      setTotalCount(total)

      // Fetch the page
      if (showAll) {
        params.skip = 0
        params.limit = total || 1000
      } else {
        params.skip = (currentPage - 1) * PAGE_SIZE
        params.limit = PAGE_SIZE
      }

      const response = await api.get('/products', { params })
      setProducts(response.data)
    } catch (error) {
      console.error('Error fetching products:', error)
    } finally {
      setLoading(false)
    }
  }

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

  const totalPages = showAll ? 1 : Math.ceil(totalCount / PAGE_SIZE)

  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); setCurrentPage(1) }}>
              <option value="latest">Latest</option>
              <option value="popular">Most Popular</option>
              <option value="brand">Brand</option>
              <option value="name">Name: A to Z</option>
              <option value="price-low">Price: Low to High</option>
              <option value="price-high">Price: High to Low</option>
            </select>
            <span className="product-count">
              {showAll
                ? `${totalCount} products (all)`
                : `${totalCount} products — page ${currentPage} of ${totalPages || 1}`}
            </span>
            <button
              onClick={() => { setShowAll(s => !s); setCurrentPage(1) }}
              className="page-btn"
            >
              {showAll ? 'Paginate' : 'Show All'}
            </button>
          </div>

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

            {/* Pagination controls (hidden when Show All is active) */}
            {!showAll && totalPages > 1 && (
              <div className="pagination">
                <button
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage <= 1}
                  className="page-btn"
                >
                  ← Prev
                </button>
                {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
                  const page = totalPages <= 7 ? i + 1 : currentPage <= 4 ? i + 1 : currentPage + i - 3
                  if (page < 1 || page > totalPages) return null
                  return (
                    <button
                      key={page}
                      onClick={() => setCurrentPage(page)}
                      className={`page-btn ${page === currentPage ? 'active' : ''}`}
                    >
                      {page}
                    </button>
                  )
                })}
                <button
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage >= totalPages}
                  className="page-btn"
                >
                  Next →
                </button>
              </div>
            )}
            </>
          ) : (
            <div className="no-products">
              <p>No products found.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
