/** FEAT-13: Abgabeverträge — Liste mit Download/Löschen (/vertraege). */
import { useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { de } from '../strings/de'
import { contractFileUrl, deleteContract, listContracts } from '../api/contracts'
import { listContactsPaged } from '../api/contacts'
import { useApi, useMutation } from '../hooks/useApi'
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 [page, setPage] = useState(1)

  const contracts = useApi(
    () => listContracts({ page, pageSize: PAGE_SIZE, orderBy: 'createdAt desc' }),
    [page],
  )
  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 (contracts.loading) return <p className="muted">{de.common.loading}</p>
  if (contracts.error || !contracts.data) {
    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>
    )
  }

  const { items, totalCount } = contracts.data
  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE))

  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" href={contractFileUrl(c)}>
                  {t.download}
                </a>
                <button
                  type="button"
                  className="btn btn--danger"
                  onClick={() => onDelete(c.id)}
                  disabled={removal.pending}
                >
                  {t.delete}
                </button>
              </span>
            </li>
          ))}
        </ul>
      )}

      {totalPages > 1 && (
        <nav className="pager" aria-label="Seitennavigation">
          <button type="button" className="btn" disabled={page <= 1} onClick={() => setPage(page - 1)}>
            {de.common.previous}
          </button>
          <span>
            {de.common.page} {page} {de.common.of} {totalPages}
          </span>
          <button
            type="button"
            className="btn"
            disabled={page >= totalPages}
            onClick={() => setPage(page + 1)}
          >
            {de.common.next}
          </button>
        </nav>
      )}
    </section>
  )
}
