import { useEffect } from 'react'
import { Facets, formatInt } from '../api'
import { FiltersBody, FilterValues } from './Filters'
import { IconClose } from './Icons'

interface Props {
  open: boolean
  facets: Facets | null
  values: FilterValues
  total: number | null
  onChange: (patch: Partial<FilterValues>) => void
  onReset: () => void
  onClose: () => void
}

/**
 * Mobile slide-up bottom sheet holding all catalog filters.
 * Backdrop tap or the close button dismisses it; filters apply live,
 * the footer button confirms and closes.
 */
export default function FilterSheet({
  open,
  facets,
  values,
  total,
  onChange,
  onReset,
  onClose,
}: Props) {
  // Scroll lock + Escape to close while open.
  useEffect(() => {
    if (!open) return
    document.body.style.overflow = 'hidden'
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    window.addEventListener('keydown', onKey)
    return () => {
      document.body.style.overflow = ''
      window.removeEventListener('keydown', onKey)
    }
  }, [open, onClose])

  if (!open) return null

  return (
    <div className="sheet-root">
      <div className="sheet-backdrop" onClick={onClose} aria-hidden="true" />
      <div
        className="sheet"
        role="dialog"
        aria-modal="true"
        aria-label="Filtres"
      >
        <div className="sheet-handle" aria-hidden="true" />
        <header className="sheet-header">
          <h2>Filtres</h2>
          <button
            type="button"
            className="sheet-close"
            onClick={onClose}
            aria-label="Fermer les filtres"
          >
            <IconClose size={20} />
          </button>
        </header>
        <div className="sheet-content">
          <FiltersBody
            facets={facets}
            values={values}
            onChange={onChange}
            idPrefix="sheet-"
          />
        </div>
        <footer className="sheet-footer">
          <button type="button" className="btn btn-secondary" onClick={onReset}>
            Réinitialiser
          </button>
          <button type="button" className="btn btn-primary" onClick={onClose}>
            {total !== null
              ? `Voir ${formatInt(total)} produit${total === 1 ? '' : 's'}`
              : 'Voir les produits'}
          </button>
        </footer>
      </div>
    </div>
  )
}
