import { useState, useEffect } from 'react';
import { Bookmark, Search, CheckCircle2, XCircle, Clock, Book, User, Calendar } from 'lucide-react';
import { Link } from 'react-router-dom';
import api from '../../store/auth';

interface LibraryReservation {
  id: number;
  uid: string;
  book_id: number;
  user_id: number;
  reservation_date: string;
  status: 'pending' | 'fulfilled' | 'cancelled';
  notes: string;
  book_title: string;
  book_author: string;
  first_name: string;
  last_name: string;
}

export default function ReservationsManagement() {
  const [reservations, setReservations] = useState<LibraryReservation[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');

  const fetchReservations = async () => {
    try {
      setLoading(true);
      const response = await api.get('/library/reservations');
      setReservations(response.data);
    } catch (error) {
      console.error('Error fetching reservations:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleCancel = async (id: number) => {
    if (!window.confirm('Are you sure you want to cancel this reservation?')) return;
    try {
      await api.put(`/library/reservations/${id}/cancel`);
      fetchReservations();
    } catch (error) {
      alert('Failed to cancel reservation');
    }
  };

  const filteredReservations = reservations.filter(r => 
    `${r.first_name} ${r.last_name}`.toLowerCase().includes(search.toLowerCase()) ||
    r.book_title.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="p-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-bold text-text flex items-center gap-2">
            <Bookmark className="text-primary" aria-hidden="true" />
            Book Reservations
          </h1>
          <p className="text-text-muted text-sm mt-1">Manage student and staff book requests</p>
        </div>
      </div>

      <div className="ng-table-container">
        <div className="p-4 border-b border-border bg-background-alt/30">
          <div className="relative w-full md:w-96">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={18} aria-hidden="true" />
            <input
              type="text"
              placeholder="Search by member or book title..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-surface border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm text-text"
            />
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="ng-table">
            <thead className="ng-table-header">
              <tr>
                <th>Book Details</th>
                <th>Requested By</th>
                <th>Request Date</th>
                <th>Status</th>
                <th className="text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50 text-sm">
              {loading ? (
                <tr><td colSpan={5} className="px-6 py-12 text-center text-text-muted">Loading records...</td></tr>
              ) : filteredReservations.length === 0 ? (
                <tr><td colSpan={5} className="px-6 py-12 text-center text-text-muted">No reservations found</td></tr>
              ) : (
                filteredReservations.map((res) => (
                  <tr key={res.id} className="ng-table-row group">
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded bg-primary-50 dark:bg-primary-900/20 flex items-center justify-center">
                          <Book size={16} className="text-primary" aria-hidden="true" />
                        </div>
                        <div>
                          <p className="font-bold text-text truncate max-w-[200px]">{res.book_title}</p>
                          <p className="text-[0.7rem] text-text-muted truncate max-w-[150px]">{res.book_author}</p>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-2">
                        <User size={14} className="text-text-muted" aria-hidden="true" />
                        <span className="font-medium text-text-secondary">{res.first_name} {res.last_name}</span>
                      </div>
                      {res.notes && (
                        <p className="text-[0.7rem] text-text-muted mt-1 italic">"{res.notes}"</p>
                      )}
                    </td>
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-2 text-xs text-text-muted">
                        <Calendar size={14} aria-hidden="true" />
                        <span>{new Date(res.reservation_date).toLocaleDateString()}</span>
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <span className={`ng-table-badge ${
                        res.status === 'fulfilled' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' : 
                        res.status === 'cancelled' ? 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 border-red-100 dark:border-red-900/30' :
                        'bg-indigo-50 dark:bg-indigo-900/20 text-indigo-700 dark:text-indigo-400 border-indigo-100 dark:border-indigo-900/30'
                      }`}>
                        {res.status}
                      </span>
                    </td>
                    <td className="ng-table-cell text-right">
                      {res.status === 'pending' && (
                        <div className="flex items-center justify-end gap-2">
                          <Link
                            to={`/library/issues?book_id=${res.book_id}&user_id=${res.user_id}`}
                            className="px-3 py-1.5 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors text-xs font-bold flex items-center gap-1.5 cursor-pointer shadow-sm"
                          >
                            <CheckCircle2 size={14} aria-hidden="true" />
                            Issue Book
                          </Link>
                          <button
                            onClick={() => handleCancel(res.id)}
                            className="px-3 py-1.5 bg-surface border border-border text-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors text-xs font-bold flex items-center gap-1.5 cursor-pointer"
                          >
                            <XCircle size={14} aria-hidden="true" />
                            Cancel
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
