/** FEAT-2: Kontakte-Liste — Quick-Chip-Filter (Rolle), Sticky-Header + Infinite Scroll. */
import { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { de } from '../strings/de'
import { listContactsPaged } from '../api/contacts'
import { andFilter, condition } from '../api/gridify'
import { useInfiniteList, useInfiniteSentinel } from '../hooks/useInfiniteList'
import {
  GerbilFilterBar,
  ActiveFilterChips,
  type FilterCategory,
} from '../components/GerbilFilterBar'
// Reuse the Rennmäuse list's sticky header + card styles for a consistent look.
import './gerbils.css'

const PAGE_SIZE = 20

export default function KontaktePage() {
  const t = de.pages.kontakte
  const [search, setSearch] = useState('')
  // Role filter: 'breeder' (Züchter) / 'receiver' (Abnehmer); multi-select.
  const [roles, setRoles] = useState<string[]>([])
  // Sticky header: collapse the title block once scrolled (IntersectionObserver sentinel).
  const [condensed, setCondensed] = useState(false)
  const topSentinelRef = useRef<HTMLDivElement | null>(null)
  useEffect(() => {
    const el = topSentinelRef.current
    if (!el) return
    const io = new IntersectionObserver(([entry]) => setCondensed(!entry.isIntersecting))
    io.observe(el)
    return () => io.disconnect()
  }, [])

  const categories: FilterCategory[] = [
    {
      key: 'rolle',
      label: t.filters.role,
      options: [
        { value: 'breeder', label: t.filters.breeder },
        { value: 'receiver', label: t.filters.receiver },
      ],
    },
  ]
  const selected = { rolle: roles }
  const toggleRole = (_key: string, value: string) =>
    setRoles((r) => (r.includes(value) ? r.filter((v) => v !== value) : [...r, value]))
  const removeRole = (_key: string, value: string) => setRoles((r) => r.filter((v) => v !== value))
  const clearAll = () => setRoles([])

  // Role conditions map to different fields, so they're OR'd into one group here
  // (rather than via orGroup which assumes a single field).
  const roleConds = [
    roles.includes('breeder') && condition({ field: 'isBreeder', op: '==', value: true }),
    roles.includes('receiver') && condition({ field: 'isReceiver', op: '==', value: true }),
  ].filter((c): c is string => Boolean(c))
  const roleFilter =
    roleConds.length === 0 ? '' : roleConds.length === 1 ? roleConds[0] : `(${roleConds.join('|')})`
  const filter = andFilter(
    search.trim() && condition({ field: 'name', op: 'contains', value: search.trim() }),
    roleFilter,
  )

  const list = useInfiniteList(
    (page) =>
      listContactsPaged({ filter: filter || undefined, orderBy: 'name,id', page, pageSize: PAGE_SIZE }),
    filter,
    'kontakte',
  )
  const sentinelRef = useInfiniteSentinel(list)
  const { items, total, hasMore, loading, loadingMore } = list

  return (
    <section className="page gerbils-page">
      <div ref={topSentinelRef} className="gerbils-scrolltop" aria-hidden="true" />

      <div className="gerbils-topbar">
        <header className={`page-head gerbils-head${condensed ? ' gerbils-head--condensed' : ''}`}>
          <div>
            <h2>{t.title}</h2>
            {!loading && (
              <p className="muted">
                {total} {t.countLabel}
              </p>
            )}
          </div>
          <Link to="/kontakte/neu" className="btn btn--primary">
            + {t.newButton}
          </Link>
        </header>

        <div className="rmf-searchbar">
          <span className="rmf-search-ico" aria-hidden="true">
            ⌕
          </span>
          <input
            type="search"
            className="rmf-searchfield"
            placeholder={t.searchPlaceholder}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            aria-label={t.fields.name}
          />
          {search && (
            <button
              type="button"
              className="rmf-search-clear"
              onClick={() => setSearch('')}
              aria-label={de.filterBar.searchClear}
            >
              ×
            </button>
          )}
        </div>

        <GerbilFilterBar categories={categories} selected={selected} onToggle={toggleRole} />
      </div>

      <ActiveFilterChips
        categories={categories}
        selected={selected}
        onRemove={removeRole}
        onClearAll={clearAll}
      />

      {loading && <p className="muted">{de.common.loading}</p>}
      {list.error && (
        <div className="alert alert--error">
          <span>{list.error}</span>
          <button type="button" className="btn" onClick={list.reload}>
            {de.common.retry}
          </button>
        </div>
      )}

      {!loading && !list.error && items.length === 0 && <p className="muted">{t.empty}</p>}

      {items.length > 0 && (
        <ul className="card-list">
          {items.map((c) => (
            <li key={c.id} className="gerbil-row">
              <Link to={`/kontakte/${c.id}`} className="gerbil-card">
                <span className="gerbil-card__name">
                  {c.name}
                  {c.isBreeder && (
                    <span
                      style={{
                        marginLeft: '0.5rem',
                        fontSize: '0.75rem',
                        padding: '0.1rem 0.4rem',
                        borderRadius: '4px',
                        background: '#e0f2fe',
                        color: '#0369a1',
                        fontWeight: 'normal',
                      }}
                    >
                      {t.filters.breeder}
                    </span>
                  )}
                  {c.isReceiver && (
                    <span
                      style={{
                        marginLeft: '0.5rem',
                        fontSize: '0.75rem',
                        padding: '0.1rem 0.4rem',
                        borderRadius: '4px',
                        background: '#fef3c7',
                        color: '#b45309',
                        fontWeight: 'normal',
                      }}
                    >
                      {t.filters.receiver}
                    </span>
                  )}
                </span>
                <span className="gerbil-card__meta">
                  {[c.phone, c.email].filter(Boolean).join(' · ')}
                </span>
              </Link>
            </li>
          ))}
        </ul>
      )}

      {/* Infinite-scroll sentinel + "loading more" indicator. */}
      {hasMore && <div ref={sentinelRef} aria-hidden="true" style={{ height: 1 }} />}
      {loadingMore && (
        <p className="muted" style={{ textAlign: 'center', padding: '0.75rem 0' }}>
          {de.common.loading}
        </p>
      )}
    </section>
  )
}
