/** FEAT-13: Abgabeverträge — Liste mit Download/Löschen (/vertraege). */
import { useMemo } from 'react'
import { Link } from 'react-router-dom'
import { de } from '../strings/de'
import { contractFileUrl, contractPdfUrl, deleteContract, listContracts } from '../api/contracts'
import { listContactsPaged } from '../api/contacts'
import { useApi, useMutation } from '../hooks/useApi'
import { useInfiniteList, useInfiniteSentinel } from '../hooks/useInfiniteList'
import { formatDate } from '../format/labels'
import './vertragWizard.css'

const PAGE_SIZE = 20

function formatPrice(price: number): string {
  return `${price.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €`
}

export default function VertraegeListPage() {
  const t = de.pages.vertraege

  const contracts = useInfiniteList(
    (page) => listContracts({ page, pageSize: PAGE_SIZE, orderBy: 'createdAt desc,id' }),
    'contracts',
    'vertraege',
  )
  const sentinelRef = useInfiniteSentinel(contracts)
  const { items, total: totalCount, loading } = contracts

  const contacts = useApi(() => listContactsPaged({ page: 1, pageSize: 1000, orderBy: 'name' }), [])
  const contactName = useMemo(
    () => new Map((contacts.data?.items ?? []).map((c) => [c.id, c.name])),
    [contacts.data],
  )

  const removal = useMutation((id: string) => deleteContract(id))
  async function onDelete(id: string) {
    if (!window.confirm(t.confirmDelete)) return
    const result = await removal.run(id)
    if (result.ok) contracts.reload()
  }

  if (loading) return <p className="muted">{de.common.loading}</p>
  if (contracts.error) {
    return (
      <section className="page">
        <h2>{t.title}</h2>
        <div className="alert alert--error">
          <span>{contracts.error}</span>
          <button type="button" className="btn" onClick={contracts.reload}>
            {de.common.retry}
          </button>
        </div>
      </section>
    )
  }

  return (
    <section className="page">
      <header className="page-head">
        <div>
          <h2>{t.title}</h2>
          <p className="muted">{t.countText(totalCount)}</p>
        </div>
        <div className="head-actions">
          <Link to="/vertraege/neu" className="btn btn--primary">
            {t.newButton}
          </Link>
        </div>
      </header>

      {removal.error && <div className="alert alert--error">{removal.error}</div>}

      {items.length === 0 ? (
        <p className="muted">{t.empty}</p>
      ) : (
        <ul className="card-list">
          {items.map((c) => (
            <li key={c.id} className="gerbil-card vertrag-card">
              <span className="gerbil-card__name">{contactName.get(c.contactId) ?? '—'}</span>
              <span className="gerbil-card__meta">
                {t.animalsCount(c.gerbilIds.length)} · {formatPrice(c.price)} ·{' '}
                {t.fields.handoverDate} {formatDate(c.handoverDate)}
              </span>
              <span className="head-actions">
                <a className="btn btn--primary" href={contractPdfUrl(c)}>
                  {t.downloadPdf}
                </a>
                {c.hasFile ? (
                  <a className="btn" href={contractFileUrl(c)}>
                    {t.download}
                  </a>
                ) : (
                  <span className="muted" title={t.noWordFile}>
                    {t.noWordFileShort}
                  </span>
                )}
                <button
                  type="button"
                  className="btn btn--danger"
                  onClick={() => onDelete(c.id)}
                  disabled={removal.pending}
                >
                  {t.delete}
                </button>
              </span>
            </li>
          ))}
        </ul>
      )}

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