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

function Borrow() {
  const [borrows, setBorrows] = useState([]);
  const [students, setStudents] = useState([]);
  const [books, setBooks] = useState([]);
  const [borrowDate, setBorrowDate] = useState('');
  const [dueDate, setDueDate] = useState('');
  const [student_FK, setStudent_FK] = useState('');
  const [book_FK, setBook_FK] = useState('');
  const [message, setMessage] = useState('');

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

  const clearForm = () => {
    setBorrowDate('');
    setDueDate('');
    setStudent_FK('');
    setBook_FK('');
  };

  const handleGet = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/borrow/getborrow', { headers });
      setBorrows(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  const loadOptions = async () => {
    try {
      const [stuRes, bookRes] = await Promise.all([
        axios.get('http://localhost:5001/api/student/getstudent', { headers }),
        axios.get('http://localhost:5001/api/book/getbook', { headers }),
      ]);
      setStudents(stuRes.data);
      setBooks(bookRes.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    handleGet();
    loadOptions();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(
        'http://localhost:5001/api/borrow/addborrow',
        { borrowDate, dueDate, student_FK, book_FK },
        { headers }
      );
      setMessage('Borrow recorded');
      clearForm();
      handleGet();
      loadOptions();
    } catch (error) {
      console.log(error);
      setMessage(error.response?.data?.msg || 'Could not borrow');
    }
  };

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

      <form onSubmit={handleSubmit} className="lms-form-panel mb-6">
        <div>
          <label className="lms-label">Student</label>
          <select
            value={student_FK}
            onChange={(e) => setStudent_FK(e.target.value)}
            className="lms-input"
            required
          >
            <option value="">Select student</option>
            {students.map((s) => (
              <option key={s._id} value={s._id}>
                {s.name} — {s.studentClass}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="lms-label">Book</label>
          <select
            value={book_FK}
            onChange={(e) => setBook_FK(e.target.value)}
            className="lms-input"
            required
          >
            <option value="">Select book</option>
            {books.map((b) => (
              <option key={b._id} value={b._id} disabled={parseInt(b.quantity, 10) <= 0}>
                {b.title} by {b.author} (copies: {b.quantity})
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="lms-label">Borrow date</label>
          <input
            type="date"
            value={borrowDate}
            onChange={(e) => setBorrowDate(e.target.value)}
            className="lms-input"
            required
          />
        </div>

        <div>
          <label className="lms-label">Due date</label>
          <input
            type="date"
            value={dueDate}
            onChange={(e) => setDueDate(e.target.value)}
            className="lms-input"
            required
          />
        </div>

        <button type="submit" className="lms-btn-primary">
          Record borrow
        </button>
      </form>

      <div className="space-y-3">
        {borrows.length === 0 ? (
          <p className="text-sm text-slate-400">No borrows recorded yet.</p>
        ) : (
          borrows.map((item) => (
            <div key={item._id} className="lms-list-item">
              <p className="font-medium text-white">{item.book_FK?.title || '—'}</p>
              <p className="mt-1 text-sm text-slate-400">Student: {item.student_FK?.name || '—'}</p>
              <p className="text-sm text-slate-400">Borrowed: {item.borrowDate} · Due: {item.dueDate}</p>
              <p className="text-sm text-slate-400">Status: {item.status}</p>
            </div>
          ))
        )}
      </div>
    </PageLayout>
  );
}

export default Borrow;
