import { useEffect, useState } from 'react';
import api from '../services/api';
import Modal from '../components/Modal';

const emptyBook = { title: '', author: '', isbn: '', category: '', quantity: 1, published_year: '' };

export default function Books() {
  const [books, setBooks] = useState([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState(emptyBook);
  const [error, setError] = useState('');

  const fetchBooks = async () => {
    setLoading(true);
    try {
      const { data } = await api.get('/books', { params: { search: search || undefined } });
      setBooks(data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchBooks(); }, []);

  const handleSearch = (e) => {
    e.preventDefault();
    fetchBooks();
  };

  const openCreate = () => {
    setEditing(null);
    setForm(emptyBook);
    setError('');
    setModalOpen(true);
  };

  const openEdit = (book) => {
    setEditing(book);
    setForm({
      title: book.title,
      author: book.author,
      isbn: book.isbn || '',
      category: book.category || '',
      quantity: book.quantity,
      published_year: book.published_year || '',
    });
    setError('');
    setModalOpen(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    try {
      const payload = {
        ...form,
        quantity: Number(form.quantity),
        published_year: form.published_year ? Number(form.published_year) : null,
      };
      if (editing) {
        await api.put(`/books/${editing.id}`, payload);
      } else {
        await api.post('/books', payload);
      }
      setModalOpen(false);
      fetchBooks();
    } catch (err) {
      setError(err.response?.data?.message || 'Operation failed.');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this book?')) return;
    try {
      await api.delete(`/books/${id}`);
      fetchBooks();
    } catch (err) {
      alert(err.response?.data?.message || 'Delete failed.');
    }
  };

  return (
    <div>
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Books</h1>
        <button onClick={openCreate} className="btn-primary">+ Add Book</button>
      </div>

      <form onSubmit={handleSearch} className="flex gap-2 mb-6">
        <input
          className="input max-w-sm"
          placeholder="Search by title, author, ISBN..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        <button type="submit" className="btn-secondary">Search</button>
      </form>

      <div className="card overflow-x-auto">
        {loading ? (
          <div className="flex justify-center py-10"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" /></div>
        ) : books.length === 0 ? (
          <p className="text-gray-500 text-center py-10">No books found. Add your first book!</p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b text-left text-gray-500">
                <th className="pb-3 pr-4">Title</th>
                <th className="pb-3 pr-4">Author</th>
                <th className="pb-3 pr-4">ISBN</th>
                <th className="pb-3 pr-4">Category</th>
                <th className="pb-3 pr-4">Qty</th>
                <th className="pb-3 pr-4">Available</th>
                <th className="pb-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {books.map((book) => (
                <tr key={book.id} className="border-b border-gray-50 hover:bg-gray-50">
                  <td className="py-3 pr-4 font-medium">{book.title}</td>
                  <td className="py-3 pr-4">{book.author}</td>
                  <td className="py-3 pr-4 text-gray-500">{book.isbn || '-'}</td>
                  <td className="py-3 pr-4">{book.category || '-'}</td>
                  <td className="py-3 pr-4">{book.quantity}</td>
                  <td className="py-3 pr-4">
                    <span className={book.available > 0 ? 'text-green-600' : 'text-red-600'}>{book.available}</span>
                  </td>
                  <td className="py-3 space-x-2">
                    <button onClick={() => openEdit(book)} className="text-primary-600 hover:underline">Edit</button>
                    <button onClick={() => handleDelete(book.id)} className="text-red-600 hover:underline">Delete</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)} title={editing ? 'Edit Book' : 'Add Book'}>
        {error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>}
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="label">Title *</label>
            <input className="input" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} required />
          </div>
          <div>
            <label className="label">Author *</label>
            <input className="input" value={form.author} onChange={(e) => setForm({ ...form, author: e.target.value })} required />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">ISBN</label>
              <input className="input" value={form.isbn} onChange={(e) => setForm({ ...form, isbn: e.target.value })} />
            </div>
            <div>
              <label className="label">Category</label>
              <input className="input" value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">Quantity</label>
              <input type="number" min="1" className="input" value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} />
            </div>
            <div>
              <label className="label">Published Year</label>
              <input type="number" className="input" value={form.published_year} onChange={(e) => setForm({ ...form, published_year: e.target.value })} />
            </div>
          </div>
          <div className="flex gap-3 pt-2">
            <button type="submit" className="btn-primary flex-1">{editing ? 'Update' : 'Create'}</button>
            <button type="button" onClick={() => setModalOpen(false)} className="btn-secondary">Cancel</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
