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

const EMPTY_FORM = {
  title: '', isbn: '', genre: '', publishedYear: '', price: '',
  totalCopies: 1, availableCopies: 1, description: '', authorId: ''
}

const GENRES = ['Dystopian','Romance','Science Fiction','Political Satire','Mystery','Thriller','Fantasy','Historical Fiction','Biography','Non-Fiction','Other']

export default function Books() {
  const [books, setBooks]     = useState([])
  const [authors, setAuthors] = useState([])
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({ title: '', genre: '', authorId: '', isAvailable: '' })
  const [modal, setModal]     = useState(null)
  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 booksApi.getAll(filters)
      setBooks(data)
    } catch (e) { toast.error(e.message) }
    finally { setLoading(false) }
  }

  useEffect(() => { authorsApi.getAll().then(setAuthors).catch(() => {}) }, [])
  useEffect(() => { load() }, [])

  const openCreate = () => { setForm(EMPTY_FORM); setEditing(null); setModal('form') }
  const openEdit   = b  => {
    setForm({
      title: b.title, isbn: b.isbn, genre: b.genre || '', publishedYear: b.publishedYear,
      price: b.price, totalCopies: b.totalCopies, availableCopies: b.availableCopies,
      description: b.description || '', authorId: b.authorId
    })
    setEditing(b)
    setModal('form')
  }

  const handleSave = async () => {
    if (!form.title.trim() || !form.isbn.trim() || !form.authorId) return toast.error('Title, ISBN and Author are required.')
    const payload = {
      ...form,
      publishedYear: parseInt(form.publishedYear),
      price: parseFloat(form.price),
      totalCopies: parseInt(form.totalCopies),
      availableCopies: editing ? parseInt(form.availableCopies) : parseInt(form.totalCopies),
      authorId: parseInt(form.authorId),
    }
    setSaving(true)
    try {
      editing ? await booksApi.update(editing.id, payload) : await booksApi.create(payload)
      toast.success(editing ? 'Book updated.' : 'Book created.')
      setModal(null); load()
    } catch (e) { toast.error(e.message) }
    finally { setSaving(false) }
  }

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

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

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Books</h1>
          <p className="page-subtitle">{books.length} book{books.length !== 1 ? 's' : ''} found</p>
        </div>
        <button className="btn btn-primary" onClick={openCreate}><IconPlus /> New Book</button>
      </div>

      <div className="filters-bar">
        <input className="filter-input" placeholder="Search title…" value={filters.title} onChange={e => filt({ title: e.target.value })} onKeyDown={e => e.key === 'Enter' && load()} />
        <select className="filter-select" value={filters.genre} onChange={e => filt({ genre: e.target.value })}>
          <option value="">All Genres</option>
          {GENRES.map(g => <option key={g} value={g}>{g}</option>)}
        </select>
        <select className="filter-select" value={filters.authorId} onChange={e => filt({ authorId: e.target.value })}>
          <option value="">All Authors</option>
          {authors.map(a => <option key={a.id} value={a.id}>{a.fullName}</option>)}
        </select>
        <select className="filter-select" value={filters.isAvailable} onChange={e => filt({ isAvailable: e.target.value })} style={{ minWidth: 130 }}>
          <option value="">Any Availability</option>
          <option value="true">Available</option>
          <option value="false">Unavailable</option>
        </select>
        <button className="btn btn-secondary" onClick={load}>Apply</button>
        <button className="btn btn-secondary" onClick={() => { setFilters({ title:'', genre:'', authorId:'', isAvailable:'' }); setTimeout(load, 0) }}>Clear</button>
      </div>

      <div className="table-wrapper">
        <table>
          <thead>
            <tr><th>Title</th><th>Author</th><th>Genre</th><th>Year</th><th>Price</th><th>Copies</th><th>Status</th><th style={{ width: 90 }}>Actions</th></tr>
          </thead>
          <tbody>
            {loading ? (
              <tr className="loading-row"><td colSpan={8}>Loading…</td></tr>
            ) : books.length === 0 ? (
              <tr><td colSpan={8} style={{ textAlign: 'center', padding: 48, color: 'var(--text-muted)' }}>No books found.</td></tr>
            ) : books.map(b => (
              <tr key={b.id}>
                <td className="td-primary">{b.title}</td>
                <td>{b.authorFullName}</td>
                <td>{b.genre ? <span className="badge badge-genre">{b.genre}</span> : <span className="text-muted">—</span>}</td>
                <td>{b.publishedYear}</td>
                <td>${Number(b.price).toFixed(2)}</td>
                <td>{b.availableCopies} / {b.totalCopies}</td>
                <td><span className={`badge ${b.isAvailable ? 'badge-available' : 'badge-unavailable'}`}>{b.isAvailable ? 'Available' : 'Out'}</span></td>
                <td>
                  <div style={{ display: 'flex', gap: 4 }}>
                    <button className="btn-icon" onClick={() => openEdit(b)}><IconEdit /></button>
                    <button className="btn-icon danger" onClick={() => setDeleting(b)}><IconTrash /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {modal === 'form' && (
        <Modal title={editing ? 'Edit Book' : 'New Book'} onClose={() => setModal(null)}>
          <div className="form-grid">
            <div className="form-group span-2">
              <label className="form-label">Title *</label>
              <input className="form-input" value={form.title} onChange={e => f({ title: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">ISBN *</label>
              <input className="form-input" value={form.isbn} onChange={e => f({ isbn: e.target.value })} placeholder="e.g. 9780451524935" />
            </div>
            <div className="form-group">
              <label className="form-label">Author *</label>
              <select className="form-select" value={form.authorId} onChange={e => f({ authorId: e.target.value })}>
                <option value="">Select author…</option>
                {authors.map(a => <option key={a.id} value={a.id}>{a.fullName}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">Genre</label>
              <select className="form-select" value={form.genre} onChange={e => f({ genre: e.target.value })}>
                <option value="">—</option>
                {GENRES.map(g => <option key={g} value={g}>{g}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">Published Year</label>
              <input className="form-input" type="number" value={form.publishedYear} onChange={e => f({ publishedYear: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">Price ($)</label>
              <input className="form-input" type="number" step="0.01" value={form.price} onChange={e => f({ price: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">Total Copies</label>
              <input className="form-input" type="number" min="1" value={form.totalCopies} onChange={e => f({ totalCopies: e.target.value })} />
            </div>
            {editing && (
              <div className="form-group">
                <label className="form-label">Available Copies</label>
                <input className="form-input" type="number" min="0" value={form.availableCopies} onChange={e => f({ availableCopies: e.target.value })} />
              </div>
            )}
            <div className="form-group span-2">
              <label className="form-label">Description</label>
              <textarea className="form-textarea" value={form.description} onChange={e => f({ description: 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 Book'}
            </button>
          </div>
        </Modal>
      )}

      {deleting && (
        <ConfirmDialog
          message={`Delete "${deleting.title}"? Books with active borrow records cannot be deleted.`}
          onConfirm={handleDelete} onCancel={() => setDeleting(null)}
        />
      )}
    </div>
  )
}
