import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { api, imgUrl } from '../api'

export default function AlbumsPage() {
  const [albums, setAlbums] = useState(null)
  const [name, setName] = useState('')
  const [error, setError] = useState(null)

  const load = () => api('/api/albums').then(setAlbums).catch((e) => setError(e.message))
  useEffect(() => {
    load()
  }, [])

  const create = async (e) => {
    e.preventDefault()
    if (!name.trim()) return
    try {
      await api('/api/albums', { method: 'POST', body: { name: name.trim() } })
      setName('')
      load()
    } catch (e) {
      setError(e.message)
    }
  }

  return (
    <>
      <div className="page-head">
        <h1>Albums</h1>
        <form className="row" onSubmit={create}>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="New album name"
          />
          <button className="btn btn-primary" type="submit">
            Create
          </button>
        </form>
      </div>
      {error && <p className="error">{error}</p>}
      {albums === null ? (
        <p className="muted">Loading…</p>
      ) : albums.length === 0 ? (
        <p className="muted">No albums yet — create one above.</p>
      ) : (
        <div className="album-grid">
          {albums.map((a) => (
            <Link key={a.id} to={`/albums/${a.id}`} className="album-card">
              <div className="album-cover">
                {a.cover_photo_id ? (
                  <img
                    src={imgUrl({ id: a.cover_photo_id, processed_at: a.cover_processed_at }, 'thumb')}
                    loading="lazy"
                    alt=""
                  />
                ) : (
                  <div className="album-cover-empty">—</div>
                )}
              </div>
              <div className="album-meta">
                <strong>{a.name}</strong>
                <span className="muted">
                  {a.photo_count} photo{a.photo_count === 1 ? '' : 's'}
                </span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </>
  )
}
