/** FEAT-2: Becken anlegen/bearbeiten — Name (Pflicht) + Notizen. */
import { useState, type FormEvent } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { de } from '../strings/de'
import { createEnclosure, getEnclosure, updateEnclosure, type CreateEnclosure } from '../api/enclosures'
import { useApi, useMutation } from '../hooks/useApi'
import { useToast } from '../components/toast'

interface FormState {
  name: string
  notes: string
  size: string
  capacity: string
  lastCleanedDate: string
  cleaningCycleDays: string
}

const EMPTY: FormState = {
  name: '',
  notes: '',
  size: '',
  capacity: '',
  lastCleanedDate: '',
  cleaningCycleDays: '',
}

/** "" -> null, sonst der Wert. */
const nn = (s: string): string | null => (s.trim() === '' ? null : s)

/** "" -> null, sonst die geparste Ganzzahl (NaN -> null). */
const ni = (s: string): number | null => {
  const t = s.trim()
  if (t === '') return null
  const n = Number.parseInt(t, 10)
  return Number.isNaN(n) ? null : n
}

export default function BeckenFormPage() {
  const t = de.pages.becken
  const navigate = useNavigate()
  const toast = useToast()
  const { id } = useParams()
  const isEdit = Boolean(id)

  const [form, setForm] = useState<FormState>(EMPTY)
  const [errors, setErrors] = useState<Partial<Record<keyof FormState, string>>>({})
  const [initializedFor, setInitializedFor] = useState<string | null>(null)

  const existing = useApi(() => (id ? getEnclosure(id) : Promise.resolve(null)), [id])

  // Vorbefüllen im Bearbeiten-Modus (adjust-state-during-render, wie FEAT-1).
  if (existing.data && initializedFor !== existing.data.id) {
    setInitializedFor(existing.data.id)
    setForm({
      name: existing.data.name,
      notes: existing.data.notes ?? '',
      size: existing.data.size ?? '',
      capacity: existing.data.capacity?.toString() ?? '',
      lastCleanedDate: existing.data.lastCleanedDate ?? '',
      cleaningCycleDays: existing.data.cleaningCycleDays?.toString() ?? '',
    })
  }

  const mutation = useMutation((body: CreateEnclosure) =>
    isEdit && id ? updateEnclosure(id, body) : createEnclosure(body),
  )

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    if (form.name.trim() === '') {
      setErrors({ name: t.validation.nameRequired })
      return
    }
    setErrors({})
    const result = await mutation.run({
      name: form.name.trim(),
      notes: nn(form.notes),
      size: nn(form.size),
      capacity: ni(form.capacity),
      lastCleanedDate: nn(form.lastCleanedDate),
      cleaningCycleDays: ni(form.cleaningCycleDays),
    })
    if (result.ok) {
      toast.success(de.common.saved)
      navigate(`/gehege/${result.value.id}`)
    } else {
      toast.error(result.error)
    }
    // On failure mutation.error also drives the inline alert; run() never throws.
  }

  if (isEdit && existing.loading) return <p className="muted">{de.common.loading}</p>

  return (
    <section className="page">
      <h2>{isEdit ? t.form.editTitle : t.form.createTitle}</h2>

      <form className="form" onSubmit={onSubmit} noValidate>
        <label className="field">
          <span>{t.fields.name} *</span>
          <input
            className="input"
            value={form.name}
            onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            aria-invalid={Boolean(errors.name)}
          />
          {errors.name && <small className="error-text">{errors.name}</small>}
        </label>

        <label className="field">
          <span>{t.fields.notes}</span>
          <textarea
            value={form.notes}
            onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
          />
        </label>

        <label className="field">
          <span>{t.fields.size}</span>
          <input
            className="input"
            value={form.size}
            placeholder="120×50 cm"
            onChange={(e) => setForm((f) => ({ ...f, size: e.target.value }))}
          />
        </label>

        <label className="field">
          <span>{t.fields.capacity}</span>
          <input
            className="input"
            type="number"
            min={0}
            value={form.capacity}
            onChange={(e) => setForm((f) => ({ ...f, capacity: e.target.value }))}
          />
        </label>

        <label className="field">
          <span>{t.fields.lastCleanedDate}</span>
          <input
            className="input"
            type="date"
            value={form.lastCleanedDate}
            onChange={(e) => setForm((f) => ({ ...f, lastCleanedDate: e.target.value }))}
          />
        </label>

        <label className="field">
          <span>{t.fields.cleaningCycleDays}</span>
          <input
            className="input"
            type="number"
            min={0}
            value={form.cleaningCycleDays}
            onChange={(e) => setForm((f) => ({ ...f, cleaningCycleDays: e.target.value }))}
          />
        </label>

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

        <div className="form-actions">
          <button type="submit" className="btn btn--primary" disabled={mutation.pending}>
            {mutation.pending ? t.form.saving : t.form.save}
          </button>
          <Link to={isEdit && id ? `/gehege/${id}` : '/gehege'} className="btn">
            {t.form.cancel}
          </Link>
        </div>
      </form>
    </section>
  )
}
