import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { authorsApi } from '../api/client'
import { Modal, ConfirmDialog, IconPlus, IconEdit, IconTrash } from '../components/UI'

const EMPTY_FORM = { firstName: '', lastName: '', nationality: '', biography: '' }

export default function Authors() {
  const [authors, setAuthors] = useState([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [modal, setModal]     = useState(null)   // null | 'create' | 'edit'
  const [editing, setEditing] = useState(null)
  const [form, setForm]       = useState(EMPTY_FORM)
  const [deleting, setDeleting] = useState(null)
  const [saving, setSaving]   = useState(false)

  const load = async () => {
    setLoading(true)
    try {
      const data = await authorsApi.getAll(search ? { name: search } : {})
      setAuthors(data)
    } catch (e) { toast.error(e.message) }
    finally { setLoading(false) }
  }

  useEffect(() => { load() }, [])

  const openCreate = () => { setForm(EMPTY_FORM); setEditing(null); setModal('form') }
  const openEdit   = a  => { setForm({ firstName: a.firstName, lastName: a.lastName, nationality: a.nationality || '', biography: a.biography || '' }); setEditing(a); setModal('form') }

  const handleSave = async () => {
    if (!form.firstName.trim() || !form.lastName.trim()) return toast.error('First and last name are required.')
    setSaving(true)
    try {
      if (editing) {
        await authorsApi.update(editing.id, form)
        toast.success('Author updated.')
      } else {
        await authorsApi.create(form)
        toast.success('Author created.')
      }
      setModal(null)
      load()
    } catch (e) { toast.error(e.message) }
    finally { setSaving(false) }
  }

  const handleDelete = async () => {
    try {
      await authorsApi.delete(deleting.id)
      toast.success('Author deleted.')
      setDeleting(null)
      load()
    } catch (e) { toast.error(e.message); setDeleting(null) }
  }

  const f = v => setForm(p => ({ ...p, ...v }))

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Authors</h1>
          <p className="page-subtitle">{authors.length} author{authors.length !== 1 ? 's' : ''} in the system</p>
        </div>
        <button className="btn btn-primary" onClick={openCreate}><IconPlus /> New Author</button>
      </div>

      <div className="filters-bar">
        <input
          className="filter-input" placeholder="Search by name…"
          value={search} onChange={e => setSearch(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && load()}
        />
        <button className="btn btn-secondary" onClick={load}>Search</button>
      </div>

      <div className="table-wrapper">
        <table>
          <thead>
            <tr>
              <th>Name</th><th>Nationality</th><th>Books</th><th>Biography</th><th style={{ width: 90 }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr className="loading-row"><td colSpan={5}>Loading…</td></tr>
            ) : authors.length === 0 ? (
              <tr><td colSpan={5} style={{ textAlign: 'center', padding: 48, color: 'var(--text-muted)' }}>No authors found.</td></tr>
            ) : authors.map(a => (
              <tr key={a.id}>
                <td className="td-primary">{a.fullName}</td>
                <td>{a.nationality || <span className="text-muted">—</span>}</td>
                <td><span className="badge badge-genre">{a.bookCount}</span></td>
                <td style={{ maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {a.biography || <span className="text-muted">—</span>}
                </td>
                <td>
                  <div style={{ display: 'flex', gap: 4 }}>
                    <button className="btn-icon" title="Edit" onClick={() => openEdit(a)}><IconEdit /></button>
                    <button className="btn-icon danger" title="Delete" onClick={() => setDeleting(a)}><IconTrash /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {modal === 'form' && (
        <Modal title={editing ? 'Edit Author' : 'New Author'} onClose={() => setModal(null)}>
          <div className="form-grid">
            <div className="form-group">
              <label className="form-label">First Name *</label>
              <input className="form-input" value={form.firstName} onChange={e => f({ firstName: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">Last Name *</label>
              <input className="form-input" value={form.lastName} onChange={e => f({ lastName: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">Nationality</label>
              <input className="form-input" value={form.nationality} onChange={e => f({ nationality: e.target.value })} />
            </div>
            <div className="form-group span-2">
              <label className="form-label">Biography</label>
              <textarea className="form-textarea" value={form.biography} onChange={e => f({ biography: e.target.value })} />
            </div>
          </div>
          <div className="form-actions">
            <button className="btn btn-secondary" onClick={() => setModal(null)}>Cancel</button>
            <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
              {saving ? 'Saving…' : editing ? 'Save Changes' : 'Create Author'}
            </button>
          </div>
        </Modal>
      )}

      {deleting && (
        <ConfirmDialog
          message={`Delete "${deleting.fullName}"? This cannot be undone. You cannot delete an author who still has books in the system.`}
          onConfirm={handleDelete}
          onCancel={() => setDeleting(null)}
        />
      )}
    </div>
  )
}
