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

export default function Borrowings() {
  const [borrowings, setBorrowings] = useState([]);
  const [books, setBooks] = useState([]);
  const [members, setMembers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [form, setForm] = useState({ book_id: '', member_id: '', due_date: '' });
  const [error, setError] = useState('');
  const [filter, setFilter] = useState('');

  const fetchData = async () => {
    setLoading(true);
    try {
      const [borRes, bookRes, memRes] = await Promise.all([
        api.get('/borrowings', { params: { status: filter || undefined } }),
        api.get('/books'),
        api.get('/members', { params: { status: 'active' } }),
      ]);
      setBorrowings(borRes.data);
      setBooks(bookRes.data.filter((b) => b.available > 0));
      setMembers(memRes.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchData(); }, [filter]);

  const handleIssue = async (e) => {
    e.preventDefault();
    setError('');
    try {
      await api.post('/borrowings', {
        book_id: Number(form.book_id),
        member_id: Number(form.member_id),
        due_date: form.due_date || undefined,
      });
      setModalOpen(false);
      setForm({ book_id: '', member_id: '', due_date: '' });
      fetchData();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to issue book.');
    }
  };

  const handleReturn = async (id) => {
    if (!confirm('Mark this book as returned?')) return;
    try {
      const { data } = await api.put(`/borrowings/${id}/return`);
      const msg = data.fine > 0 ? `Book returned. Fine: $${data.fine}` : 'Book returned successfully.';
      alert(msg);
      fetchData();
    } catch (err) {
      alert(err.response?.data?.message || 'Return failed.');
    }
  };

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

  const defaultDue = () => {
    const d = new Date();
    d.setDate(d.getDate() + 14);
    return d.toISOString().split('T')[0];
  };

  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">Borrowings</h1>
        <button onClick={() => { setError(''); setModalOpen(true); }} className="btn-primary">+ Issue Book</button>
      </div>

      <div className="flex gap-2 mb-6">
        {['', 'borrowed', 'returned'].map((s) => (
          <button
            key={s || 'all'}
            onClick={() => setFilter(s)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
              filter === s ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`}
          >
            {s === '' ? 'All' : s.charAt(0).toUpperCase() + s.slice(1)}
          </button>
        ))}
      </div>

      <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>
        ) : borrowings.length === 0 ? (
          <p className="text-gray-500 text-center py-10">No borrowing records.</p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b text-left text-gray-500">
                <th className="pb-3 pr-4">Book</th>
                <th className="pb-3 pr-4">Member</th>
                <th className="pb-3 pr-4">Borrowed</th>
                <th className="pb-3 pr-4">Due Date</th>
                <th className="pb-3 pr-4">Returned</th>
                <th className="pb-3 pr-4">Status</th>
                <th className="pb-3 pr-4">Fine</th>
                <th className="pb-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {borrowings.map((b) => {
                const overdue = b.status === 'borrowed' && b.due_date < new Date().toISOString().split('T')[0];
                return (
                  <tr key={b.id} className="border-b border-gray-50 hover:bg-gray-50">
                    <td className="py-3 pr-4 font-medium">{b.book_title}</td>
                    <td className="py-3 pr-4">{b.member_name}</td>
                    <td className="py-3 pr-4">{b.borrow_date?.split('T')[0]}</td>
                    <td className={`py-3 pr-4 ${overdue ? 'text-red-600 font-medium' : ''}`}>{b.due_date?.split('T')[0]}</td>
                    <td className="py-3 pr-4">{b.return_date?.split('T')[0] || '-'}</td>
                    <td className="py-3 pr-4">
                      <span className={`px-2 py-1 rounded-full text-xs ${
                        b.status === 'borrowed'
                          ? overdue ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
                          : 'bg-green-100 text-green-800'
                      }`}>
                        {overdue ? 'overdue' : b.status}
                      </span>
                    </td>
                    <td className="py-3 pr-4">{b.fine > 0 ? `$${b.fine}` : '-'}</td>
                    <td className="py-3 space-x-2 whitespace-nowrap">
                      {b.status === 'borrowed' && (
                        <button onClick={() => handleReturn(b.id)} className="text-green-600 hover:underline">Return</button>
                      )}
                      <button onClick={() => handleDelete(b.id)} className="text-red-600 hover:underline">Delete</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)} title="Issue Book">
        {error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded-lg text-sm">{error}</div>}
        <form onSubmit={handleIssue} className="space-y-4">
          <div>
            <label className="label">Book *</label>
            <select className="input" value={form.book_id} onChange={(e) => setForm({ ...form, book_id: e.target.value })} required>
              <option value="">Select a book</option>
              {books.map((b) => (
                <option key={b.id} value={b.id}>{b.title} — {b.author} ({b.available} avail.)</option>
              ))}
            </select>
          </div>
          <div>
            <label className="label">Member *</label>
            <select className="input" value={form.member_id} onChange={(e) => setForm({ ...form, member_id: e.target.value })} required>
              <option value="">Select a member</option>
              {members.map((m) => (
                <option key={m.id} value={m.id}>{m.name} ({m.email})</option>
              ))}
            </select>
          </div>
          <div>
            <label className="label">Due Date</label>
            <input
              type="date"
              className="input"
              value={form.due_date || defaultDue()}
              onChange={(e) => setForm({ ...form, due_date: e.target.value })}
            />
          </div>
          <div className="flex gap-3 pt-2">
            <button type="submit" className="btn-primary flex-1">Issue Book</button>
            <button type="button" onClick={() => setModalOpen(false)} className="btn-secondary">Cancel</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
