import React, { useEffect, useState } from 'react';
import axios from 'axios';
import PageLayout from '../components/PageLayout';

function Books() {
  const [books, setBooks] = useState([]);
  const [user, setUser] = useState(null);
  const [title, setTitle] = useState('');
  const [author, setAuthor] = useState('');
  const [quantity, setQuantity] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setTitle('');
    setAuthor('');
    setQuantity('');
  };

  const getBooks = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/book/getbook', { headers });
      setBooks(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    const stored = localStorage.getItem('user');
    if (stored) setUser(JSON.parse(stored));
    getBooks();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/book/updatebook/${editId}`,
          { title, author, quantity },
          { headers }
        );
        setMessage('Book updated');
      } else {
        await axios.post(
          'http://localhost:5001/api/book/addbook',
          { title, author, quantity },
          { headers }
        );
        setMessage('Book added');
      }
      clearForm();
      setEditId(null);
      getBooks();
    } catch (err) {
      console.log(err);
      setMessage(err.response?.data?.message || 'Action failed');
    }
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5001/api/book/deletebook/${id}`, { headers });
      getBooks();
    } catch (err) {
      console.log(err);
    }
  };

  const handleEdit = (book) => {
    setTitle(book.title);
    setAuthor(book.author);
    setQuantity(book.quantity);
    setEditId(book._id);
  };

  const isAdmin = user && user.role === 'admin';

  return (
    <PageLayout title="Book management">
      {message && <p className="lms-alert-success">{message}</p>}

      {isAdmin && (
        <form onSubmit={handleSubmit} className="lms-form-panel mb-6">
          <input
            type="text"
            placeholder="Title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="lms-input"
            required
          />
          <input
            type="text"
            placeholder="Author"
            value={author}
            onChange={(e) => setAuthor(e.target.value)}
            className="lms-input"
            required
          />
          <input
            type="number"
            placeholder="Quantity (copies)"
            value={quantity}
            onChange={(e) => setQuantity(e.target.value)}
            className="lms-input"
            required
          />
          <button type="submit" className="lms-btn-primary">
            {editId ? 'Update' : 'Add book'}
          </button>
        </form>
      )}

      <div className="space-y-3">
        {books.map((book) => (
          <div key={book._id} className="lms-list-item">
            <p className="font-medium text-white">{book.title}</p>
            <p className="mt-1 text-sm text-slate-400">Author: {book.author}</p>
            <p className="text-sm text-slate-400">Copies available: {book.quantity}</p>
            {isAdmin && (
              <div className="mt-3 flex gap-4 text-sm">
                <button type="button" onClick={() => handleEdit(book)} className="text-blue-400 hover:text-blue-300">
                  Edit
                </button>
                <button type="button" onClick={() => handleDelete(book._id)} className="text-red-400 hover:text-red-300">
                  Delete
                </button>
              </div>
            )}
          </div>
        ))}
      </div>
    </PageLayout>
  );
}

export default Books;
