/** Bilder eines Gehges — Galerie-Raster + Upload + Löschen (wie der Tier-Fotos-Tab). */
import { useRef, useState, type FormEvent } from 'react'
import { de } from '../strings/de'
import {
  deleteEnclosurePhoto,
  listEnclosurePhotos,
  photoSrc,
  uploadEnclosurePhoto,
} from '../api/enclosurePhotos'
import { useApi, useMutation } from '../hooks/useApi'
import { useToast } from './toast'

export default function EnclosurePhotosSection({ enclosureId }: { enclosureId: string }) {
  const tp = de.pages.tierTabs.photos
  const toast = useToast()

  const photos = useApi(() => listEnclosurePhotos(enclosureId), [enclosureId])
  const fileInput = useRef<HTMLInputElement>(null)
  const [caption, setCaption] = useState('')
  const [fileError, setFileError] = useState<string | null>(null)

  const upload = useMutation((file: File) =>
    uploadEnclosurePhoto(enclosureId, file, caption.trim() === '' ? null : caption.trim()),
  )
  const removal = useMutation((photoId: string) => deleteEnclosurePhoto(photoId))

  async function onUpload(e: FormEvent) {
    e.preventDefault()
    const file = fileInput.current?.files?.[0]
    if (!file) {
      setFileError(tp.validation.fileRequired)
      return
    }
    setFileError(null)
    const r = await upload.run(file)
    if (r.ok) {
      toast.success(de.common.saved)
      setCaption('')
      if (fileInput.current) fileInput.current.value = ''
      photos.reload()
    } else {
      toast.error(r.error)
    }
  }

  async function onDelete(photoId: string) {
    if (!window.confirm(tp.deleteConfirm)) return
    const r = await removal.run(photoId)
    if (r.ok) {
      toast.success(de.common.deleted)
      photos.reload()
    } else {
      toast.error(r.error)
    }
  }

  const items = photos.data ?? []

  return (
    <div>
      <form className="form" onSubmit={onUpload} noValidate>
        <label className="field">
          <span>{tp.chooseFile}</span>
          <input ref={fileInput} type="file" accept="image/*" className="input" />
          {fileError && <small className="error-text">{fileError}</small>}
        </label>
        <label className="field">
          <span>{tp.captionLabel}</span>
          <input className="input" value={caption} onChange={(e) => setCaption(e.target.value)} />
        </label>
        {upload.error && <div className="alert alert--error">{upload.error}</div>}
        <div className="form-actions">
          <button type="submit" className="btn btn--primary" disabled={upload.pending}>
            {upload.pending ? tp.uploading : tp.uploadButton}
          </button>
        </div>
      </form>

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

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

      {items.length > 0 && (
        <ul className="photo-grid">
          {[...items]
            .sort((a, b) => a.sortOrder - b.sortOrder)
            .map((p) => (
              <li key={p.id} className="photo-card">
                <img src={photoSrc(p)} alt={p.caption ?? p.fileName} loading="lazy" />
                <div className="photo-card__bar">
                  <span className="photo-card__caption">{p.caption ?? ''}</span>
                  <button
                    type="button"
                    className="btn btn--danger"
                    onClick={() => onDelete(p.id)}
                    disabled={removal.pending}
                  >
                    {de.common.delete}
                  </button>
                </div>
              </li>
            ))}
        </ul>
      )}
    </div>
  )
}
