import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { fetchProducts, Product, ProductQuery } from '../api'
import { IconArrowRight } from './Icons'
import ProductCard from './ProductCard'
import { SkeletonRow } from './Skeleton'

interface RailProps {
  title: string
  query: ProductQuery
  seeAllHref?: string
}

export default function Rail({ title, query, seeAllHref }: RailProps) {
  const [products, setProducts] = useState<Product[] | null>(null)
  const [error, setError] = useState(false)

  useEffect(() => {
    const controller = new AbortController()
    setProducts(null)
    setError(false)
    fetchProducts({ per_page: 12, ...query }, controller.signal)
      .then((res) => setProducts(res.items))
      .catch((err: unknown) => {
        if (err instanceof DOMException && err.name === 'AbortError') return
        setError(true)
        setProducts([])
      })
    return () => controller.abort()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(query)])

  if (error || (products !== null && products.length === 0)) {
    return null
  }

  return (
    <section className="rail">
      <header className="section-header">
        <h2>{title}</h2>
        {seeAllHref && (
          <Link className="section-see-all" to={seeAllHref}>
            Tout voir <IconArrowRight size={15} />
          </Link>
        )}
      </header>
      {products === null ? (
        <SkeletonRow count={6} />
      ) : (
        <div className="rail-track">
          {products.map((p) => (
            <div className="rail-item" key={p.uid}>
              <ProductCard product={p} />
            </div>
          ))}
        </div>
      )}
    </section>
  )
}
