/** FEAT-2: Kontakt anlegen/bearbeiten — Name (Pflicht), E-Mail/Telefon/Adresse, Notizen.
 * (FEAT-13: strukturierte Felder statt Freitext-Kontaktdaten — Käufer-Block der Verträge.) */
import { useState, type FormEvent } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { de } from '../strings/de'
import { createContact, getContact, updateContact, type CreateContact } from '../api/contacts'
import { useApi, useMutation } from '../hooks/useApi'

interface FormState {
  name: string
  email: string
  phone: string
  address: string
  notes: string
}

const EMPTY: FormState = { name: '', email: '', phone: '', address: '', notes: '' }

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

export default function KontaktFormPage() {
  const t = de.pages.kontakte
  const navigate = useNavigate()
  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 ? getContact(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,
      email: existing.data.email ?? '',
      phone: existing.data.phone ?? '',
      address: existing.data.address ?? '',
      notes: existing.data.notes ?? '',
    })
  }

  const set = <K extends keyof FormState>(key: K, value: FormState[K]) =>
    setForm((f) => ({ ...f, [key]: value }))

  const mutation = useMutation((body: CreateContact) =>
    isEdit && id ? updateContact(id, body) : createContact(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(),
      email: nn(form.email),
      phone: nn(form.phone),
      address: nn(form.address),
      notes: nn(form.notes),
    })
    if (result.ok) navigate(`/kontakte/${result.value.id}`)
    // On failure mutation.error 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) => set('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.email}</span>
          <input
            className="input"
            type="email"
            value={form.email}
            onChange={(e) => set('email', e.target.value)}
          />
        </label>

        <label className="field">
          <span>{t.fields.phone}</span>
          <input
            className="input"
            type="tel"
            value={form.phone}
            onChange={(e) => set('phone', e.target.value)}
          />
        </label>

        <label className="field">
          <span>{t.fields.address}</span>
          <input
            className="input"
            value={form.address}
            onChange={(e) => set('address', e.target.value)}
          />
          <small className="muted">{t.form.addressHint}</small>
        </label>

        <label className="field">
          <span>{t.fields.notes}</span>
          <textarea value={form.notes} onChange={(e) => set('notes', 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 ? `/kontakte/${id}` : '/kontakte'} className="btn">
            {t.form.cancel}
          </Link>
        </div>
      </form>
    </section>
  )
}
