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

function Return() {
  const [borrowed, setBorrowed] = useState([]);
  const [message, setMessage] = useState('');

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

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

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

  const handleReturn = async (id) => {
    try {
      await axios.put(`http://localhost:5001/api/borrow/returnborrow/${id}`, {}, { headers });
      setMessage('Book returned — copy added back to inventory');
      handleGet();
    } catch (error) {
      console.log(error);
      setMessage(error.response?.data?.msg || 'Return failed');
    }
  };

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

      <div className="space-y-3">
        {borrowed.length === 0 ? (
          <p className="text-sm text-slate-400">No books currently out on loan.</p>
        ) : (
          borrowed.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>
              <button
                type="button"
                onClick={() => handleReturn(item._id)}
                className="lms-btn-primary mt-3 bg-green-600 hover:bg-green-700"
              >
                Return book
              </button>
            </div>
          ))
        )}
      </div>
    </PageLayout>
  );
}

export default Return;
