import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Facets, fetchFacets, fetchStats, formatInt, Stats } from '../api'
import CountUp from '../components/CountUp'
import { categoryIcon, IconArrowRight } from '../components/Icons'
import Rail from '../components/Rail'
import SearchBar from '../components/SearchBar'
import Skeleton from '../components/Skeleton'

interface RailDef {
  title: string
  category?: string
  seeAllHref: string
}

function pickCategory(
  facets: Facets | null,
  keywords: string[]
): string | undefined {
  if (!facets) return undefined
  const found = facets.categories.find((c) =>
    keywords.some(
      (k) =>
        c.key.toLowerCase().includes(k) || c.label.toLowerCase().includes(k)
    )
  )
  return found?.key
}

export default function Home() {
  const [stats, setStats] = useState<Stats | null>(null)
  const [facets, setFacets] = useState<Facets | null>(null)

  useEffect(() => {
    const controller = new AbortController()
    fetchStats(controller.signal)
      .then(setStats)
      .catch(() => {})
    fetchFacets(controller.signal)
      .then(setFacets)
      .catch(() => {})
    return () => controller.abort()
  }, [])

  const rails: RailDef[] = [
    { title: 'Nouveautés', seeAllHref: '/produits?sort=recent' },
  ]
  const erable = pickCategory(facets, ['érable', 'erable', 'miel'])
  if (erable) {
    rails.push({
      title: 'Érable & miel',
      category: erable,
      seeAllHref: `/produits?category=${encodeURIComponent(erable)}`,
    })
  }
  const beaute = pickCategory(facets, ['beauté', 'beaute', 'soins'])
  if (beaute) {
    rails.push({
      title: 'Beauté & soins',
      category: beaute,
      seeAllHref: `/produits?category=${encodeURIComponent(beaute)}`,
    })
  }
  const maison = pickCategory(facets, ['maison', 'déco', 'deco'])
  if (maison) {
    rails.push({
      title: 'Maison & déco',
      category: maison,
      seeAllHref: `/produits?category=${encodeURIComponent(maison)}`,
    })
  }

  return (
    <div className="page home">
      <section className="hero">
        <p className="hero-eyebrow">Le répertoire des produits d'ici</p>
        <h1 className="hero-title">
          Tous les produits québécois.
          <br />
          <em>Un seul endroit.</em>
        </h1>
        <p className="hero-sub">
          Fabri-Ka rassemble les catalogues des boutiques en ligne d'ici —
          fabriqué, conçu et vendu au Québec.
        </p>

        <div className="hero-search">
          <SearchBar />
        </div>

        <div className="hero-stats">
          {stats ? (
            <>
              <div className="stat">
                <span className="stat-number">
                  <CountUp value={stats.totals.products} />
                </span>
                <span className="stat-label">Produits</span>
              </div>
              <div className="stat">
                <span className="stat-number">
                  <CountUp value={stats.totals.stores_live} />
                </span>
                <span className="stat-label">Boutiques</span>
              </div>
              <div className="stat">
                <span className="stat-number">
                  <CountUp value={stats.totals.regions} />
                </span>
                <span className="stat-label">Régions</span>
              </div>
            </>
          ) : (
            <>
              <Skeleton width="90px" height="3rem" />
              <Skeleton width="90px" height="3rem" />
              <Skeleton width="90px" height="3rem" />
            </>
          )}
        </div>
        <Link className="hero-stats-link" to="/stats">
          Statistiques <IconArrowRight size={14} />
        </Link>
      </section>

      <section className="home-categories" aria-label="Catégories">
        <header className="section-header">
          <h2>Parcourir par catégorie</h2>
          <Link className="section-see-all" to="/produits">
            Tout le catalogue <IconArrowRight size={15} />
          </Link>
        </header>
        <div className="category-chips">
          {facets ? (
            facets.categories.map((c) => (
              <Link
                key={c.key}
                className="chip"
                to={`/produits?category=${encodeURIComponent(c.key)}`}
              >
                <span className="chip-icon" aria-hidden="true">
                  {categoryIcon(c.label)}
                </span>
                {c.label}
                <span className="chip-count">{formatInt(c.n)}</span>
              </Link>
            ))
          ) : (
            <>
              <Skeleton width="110px" height="2.5rem" radius="999px" />
              <Skeleton width="140px" height="2.5rem" radius="999px" />
              <Skeleton width="120px" height="2.5rem" radius="999px" />
              <Skeleton width="100px" height="2.5rem" radius="999px" />
            </>
          )}
        </div>
      </section>

      {rails.map((r) => (
        <Rail
          key={r.title}
          title={r.title}
          query={
            r.category
              ? { category: r.category, per_page: 12 }
              : { sort: 'recent', per_page: 12 }
          }
          seeAllHref={r.seeAllHref}
        />
      ))}
    </div>
  )
}
