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

const EMPTY_FORM = {
  borrowerName: '', borrowerEmail: '', bookId: '',
  borrowDate: new Date().toISOString().slice(0, 10),
  dueDate: '', notes: '', status: 'Active', returnDate: ''
}

const statusClass = s => ({ Active: 'badge-active', Returned: 'badge-returned', Overdue: 'badge-overdue' }[s] || '')

export default function BorrowRecords() {
  const [records, setRecords] = useState([])
  const [books, setBooks]     = useState([])
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({ borrowerName: '', bookId: '', status: '', isOverdue: '' })
  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 { setRecords(await borrowApi.getAll(filters)) }
    catch (e) { toast.error(e.message) }
    finally { setLoading(false) }
  }

  useEffect(() => { booksApi.getAll().then(setBooks).catch(() => {}) }, [])
  useEffect(() => { load() }, [])

  const openCreate = () => { setForm(EMPTY_FORM); setEditing(null); setModal('form') }
  const openEdit   = r  => {
    setForm({
      borrowerName: r.borrowerName, borrowerEmail: r.borrowerEmail,
      bookId: r.bookId,
      borrowDate: r.borrowDate?.slice(0, 10) || '',
      dueDate: r.dueDate?.slice(0, 10) || '',
      returnDate: r.returnDate?.slice(0, 10) || '',
      status: r.status, notes: r.notes || ''
    })
    setEditing(r); setModal('form')
  }

  const handleSave = async () => {
    if (!form.borrowerName.trim() || !form.borrowerEmail.trim() || !form.bookId || !form.dueDate)
      return toast.error('Name, email, book and due date are required.')
    const payload = {
      borrowerName: form.borrowerName, borrowerEmail: form.borrowerEmail,
      bookId: parseInt(form.bookId),
      borrowDate: new Date(form.borrowDate).toISOString(),
      dueDate: new Date(form.dueDate).toISOString(),
      returnDate: form.returnDate ? new Date(form.returnDate).toISOString() : null,
      status: form.status, notes: form.notes || null
    }
    setSaving(true)
    try {
      editing ? await borrowApi.update(editing.id, payload) : await borrowApi.create(payload)
      toast.success(editing ? 'Record updated.' : 'Borrow record created.')
      setModal(null); load()
    } catch (e) { toast.error(e.message) }
    finally { setSaving(false) }
  }

  const handleDelete = async () => {
    try { await borrowApi.delete(deleting.id); toast.success('Record 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 }))

  const fmt = d => d ? new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) : '—'

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

      <div className="filters-bar">
        <input className="filter-input" placeholder="Search borrower…" value={filters.borrowerName} onChange={e => filt({ borrowerName: e.target.value })} onKeyDown={e => e.key === 'Enter' && load()} />
        <select className="filter-select" value={filters.bookId} onChange={e => filt({ bookId: e.target.value })}>
          <option value="">All Books</option>
          {books.map(b => <option key={b.id} value={b.id}>{b.title}</option>)}
        </select>
        <select className="filter-select" value={filters.status} onChange={e => filt({ status: e.target.value })}>
          <option value="">All Statuses</option>
          <option value="Active">Active</option>
          <option value="Returned">Returned</option>
          <option value="Overdue">Overdue</option>
        </select>
        <select className="filter-select" value={filters.isOverdue} onChange={e => filt({ isOverdue: e.target.value })} style={{ minWidth: 130 }}>
          <option value="">All</option>
          <option value="true">Overdue Only</option>
        </select>
        <button className="btn btn-secondary" onClick={load}>Apply</button>
        <button className="btn btn-secondary" onClick={() => { setFilters({ borrowerName:'', bookId:'', status:'', isOverdue:'' }); setTimeout(load, 0) }}>Clear</button>
      </div>

      <div className="table-wrapper">
        <table>
          <thead>
            <tr><th>Borrower</th><th>Book</th><th>Borrow Date</th><th>Due Date</th><th>Return Date</th><th>Status</th><th style={{ width: 90 }}>Actions</th></tr>
          </thead>
          <tbody>
            {loading ? (
              <tr className="loading-row"><td colSpan={7}>Loading…</td></tr>
            ) : records.length === 0 ? (
              <tr><td colSpan={7} style={{ textAlign: 'center', padding: 48, color: 'var(--text-muted)' }}>No records found.</td></tr>
            ) : records.map(r => (
              <tr key={r.id} className={r.isOverdue ? 'overdue-row' : ''}>
                <td>
                  <div className="td-primary">{r.borrowerName}</div>
                  <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>{r.borrowerEmail}</div>
                </td>
                <td>
                  <div className="td-primary">{r.bookTitle}</div>
                  <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>{r.authorFullName}</div>
                </td>
                <td>{fmt(r.borrowDate)}</td>
                <td style={{ color: r.isOverdue ? 'var(--red)' : 'inherit' }}>{fmt(r.dueDate)}</td>
                <td>{fmt(r.returnDate)}</td>
                <td>
                  <span className={`badge ${statusClass(r.status)}`}>{r.status}</span>
                  {r.daysOverdue > 0 && <span style={{ fontSize: '0.72rem', color: 'var(--red)', marginLeft: 6 }}>{r.daysOverdue}d</span>}
                </td>
                <td>
                  <div style={{ display: 'flex', gap: 4 }}>
                    <button className="btn-icon" onClick={() => openEdit(r)}><IconEdit /></button>
                    <button className="btn-icon danger" onClick={() => setDeleting(r)}><IconTrash /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {modal === 'form' && (
        <Modal title={editing ? 'Edit Borrow Record' : 'New Borrow Record'} onClose={() => setModal(null)}>
          <div className="form-grid">
            <div className="form-group">
              <label className="form-label">Borrower Name *</label>
              <input className="form-input" value={form.borrowerName} onChange={e => f({ borrowerName: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">Borrower Email *</label>
              <input className="form-input" type="email" value={form.borrowerEmail} onChange={e => f({ borrowerEmail: e.target.value })} />
            </div>
            <div className="form-group span-2">
              <label className="form-label">Book *</label>
              <select className="form-select" value={form.bookId} onChange={e => f({ bookId: e.target.value })} disabled={!!editing}>
                <option value="">Select book…</option>
                {books.map(b => <option key={b.id} value={b.id}>{b.title} ({b.availableCopies} available)</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">Borrow Date</label>
              <input className="form-input" type="date" value={form.borrowDate} onChange={e => f({ borrowDate: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">Due Date *</label>
              <input className="form-input" type="date" value={form.dueDate} onChange={e => f({ dueDate: e.target.value })} />
            </div>
            {editing && (<>
              <div className="form-group">
                <label className="form-label">Return Date</label>
                <input className="form-input" type="date" value={form.returnDate} onChange={e => f({ returnDate: e.target.value })} />
              </div>
              <div className="form-group">
                <label className="form-label">Status</label>
                <select className="form-select" value={form.status} onChange={e => f({ status: e.target.value })}>
                  <option value="Active">Active</option>
                  <option value="Returned">Returned</option>
                  <option value="Overdue">Overdue</option>
                </select>
              </div>
            </>)}
            <div className="form-group span-2">
              <label className="form-label">Notes</label>
              <textarea className="form-textarea" value={form.notes} onChange={e => f({ notes: 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 Record'}
            </button>
          </div>
        </Modal>
      )}

      {deleting && (
        <ConfirmDialog
          message={`Delete borrow record for "${deleting.borrowerName} — ${deleting.bookTitle}"? Only returned records can be deleted.`}
          onConfirm={handleDelete} onCancel={() => setDeleting(null)}
        />
      )}
    </div>
  )
}
