import { useEffect, useState, useRef } from 'react';
import { useLibraryStore, Book } from '../../store/library';
import api from '../../store/auth';
import { Modal, ModalBody } from '../../components/ui/Modal';
import { 
  Book as BookIcon, BookOpen, Library as LibraryIcon, 
  Search, Plus, Download,
  ChevronRight, Bookmark, Clock, CheckCircle2,
  Trash2, Edit2, BookmarkPlus,
  MapPin, Hash, X, HandCoins, CalendarClock
} from 'lucide-react';

/** Trigger a CSV download of the current list state. */
function exportToCsv(filename: string, rows: Record<string, unknown>[]) {
  if (rows.length === 0) return;
  const headers = Object.keys(rows[0]);
  const escape = (v: unknown) => {
    const s = v == null ? '' : String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const csv = [headers.join(','), ...rows.map(r => headers.map(h => escape(r[h])).join(','))].join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

export default function Library() {
  const { 
    books, issues, reservations, fines, loading,
    fetchBooks, fetchIssues, fetchReservations, fetchFines,
    addBook, updateBook, deleteBook, issueBook, returnBook,
    reserveBook, cancelReservation, payFine, waiveFine
  } = useLibraryStore();

  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingBook, setEditingBook] = useState<Book | null>(null);
  const [activeTab, setActiveTab] = useState('books'); // books, issues, reservations, fines
  
  const [form, setForm] = useState({
    isbn: '',
    title: '',
    author: '',
    category: '',
    publisher: '',
    year_published: '',
    total_copies: 1,
    shelf_location: '',
  });

  const [users, setUsers] = useState<any[]>([]);
  const [showIssueModal, setShowIssueModal] = useState(false);
  const [selectedBookForIssue, setSelectedBookForIssue] = useState<Book | null>(null);
  const [userSearch, setUserSearch] = useState('');
  const [selectedUser, setSelectedUser] = useState<any | null>(null);
  const [showUserDropdown, setShowUserDropdown] = useState(false);
  const [issueDueDate, setIssueDueDate] = useState('');

  const [showReturnModal, setShowReturnModal] = useState(false);
  const [selectedIssueForReturn, setSelectedIssueForReturn] = useState<any | null>(null);
  const [returnFineChecked, setReturnFineChecked] = useState(false);
  const [returnFineAmount, setReturnFineAmount] = useState(0);
  const [returnFineReason, setReturnFineReason] = useState('Late Return');

  const [borrowerRoleFilter, setBorrowerRoleFilter] = useState<'all' | 'student' | 'teacher'>('all');
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowUserDropdown(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    fetchBooks();
    fetchIssues();
    fetchReservations();
    fetchFines();
    loadUsers();
  }, []);

  const loadUsers = async () => {
    try {
      const res = await api.get('/users', { params: { limit: 1000 } });
      const data = res.data.users || res.data;
      setUsers(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error('Failed to load user directory for library');
    }
  };

  const openIssueModal = (book: Book) => {
    setSelectedBookForIssue(book);
    setUserSearch('');
    setSelectedUser(null);
    setShowUserDropdown(false);
    setBorrowerRoleFilter('all');
    
    const defaultDate = new Date();
    defaultDate.setDate(defaultDate.getDate() + 14);
    setIssueDueDate(defaultDate.toISOString().split('T')[0]);
    
    setShowIssueModal(true);
  };

  const handleIssueBook = async () => {
    if (!selectedBookForIssue || !selectedUser) {
      alert('Please select a borrower');
      return;
    }
    try {
      await issueBook({ 
        book_id: selectedBookForIssue.id, 
        user_id: selectedUser.id, 
        due_date: issueDueDate 
      });
      setShowIssueModal(false);
      alert('Asset circulation initiated successfully');
    } catch (err: any) {
      alert(err.response?.data?.error || 'Protocol failure');
    }
  };

  const openReturnModal = (issue: any) => {
    setSelectedIssueForReturn(issue);
    setReturnFineChecked(false);
    setReturnFineAmount(0);
    setReturnFineReason('Late Return');
    setShowReturnModal(true);
  };

  const handleReturnBook = async () => {
    if (!selectedIssueForReturn) return;
    try {
      await returnBook(selectedIssueForReturn.id, {
        generate_fine: returnFineChecked,
        fine_amount: returnFineChecked ? Number(returnFineAmount) : 0,
        fine_reason: returnFineChecked ? returnFineReason : ''
      });
      setShowReturnModal(false);
      alert('Asset returned successfully');
    } catch (err: any) {
      alert(err.response?.data?.error || 'Return failed');
    }
  };

  const applyReturnPreset = (amount: number, reason: string) => {
    if (amount > 0) {
      setReturnFineChecked(true);
      setReturnFineAmount(amount);
      setReturnFineReason(reason);
    } else {
      setReturnFineChecked(false);
      setReturnFineAmount(0);
      setReturnFineReason('');
    }
  };

  const saveBook = async () => {
    try {
      const payload = {
        ...form,
        year_published: Number(form.year_published),
        total_copies: Number(form.total_copies),
      };

      if (editingBook) {
        await updateBook(editingBook.id, payload);
      } else {
        await addBook(payload);
      }
      setShowModal(false);
      setEditingBook(null);
      setForm({
        isbn: '', title: '', author: '', category: '', publisher: '', 
        year_published: '', total_copies: 1, shelf_location: '',
      });
    } catch (err) {
      console.error(err);
      alert('Failed to save book record');
    }
  };

  const filteredBooks = books.filter(b => 
    (b.title || '').toLowerCase().includes(search.toLowerCase()) ||
    (b.author || '').toLowerCase().includes(search.toLowerCase()) ||
    (b.isbn || '').toLowerCase().includes(search.toLowerCase()) ||
    (b.category || '').toLowerCase().includes(search.toLowerCase())
  );

  const filteredIssues = issues.filter(i => 
    (i.book_title || '').toLowerCase().includes(search.toLowerCase()) ||
    (`${i.first_name || ''} ${i.last_name || ''}`).toLowerCase().includes(search.toLowerCase()) ||
    (i.status || '').toLowerCase().includes(search.toLowerCase())
  );

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

  const filteredFines = fines.filter(f => 
    (f.book_title || '').toLowerCase().includes(search.toLowerCase()) ||
    (`${f.first_name || ''} ${f.last_name || ''}`).toLowerCase().includes(search.toLowerCase()) ||
    (f.reason || '').toLowerCase().includes(search.toLowerCase()) ||
    (f.status || '').toLowerCase().includes(search.toLowerCase())
  );

  const filteredUsersForIssue = users.filter(u => {
    const isEligible = u.role === 'student' || u.role === 'teacher';
    if (!isEligible) return false;

    if (borrowerRoleFilter !== 'all' && u.role !== borrowerRoleFilter) return false;

    const isSearchActive = userSearch && (!selectedUser || userSearch !== `${selectedUser.first_name} ${selectedUser.last_name} (${selectedUser.role.toUpperCase()})`);
    if (isSearchActive) {
      const fullName = `${u.first_name || ''} ${u.last_name || ''}`.toLowerCase();
      const email = (u.email || '').toLowerCase();
      const query = userSearch.toLowerCase();
      const idNum = (u.id_number || '').toLowerCase();
      return fullName.includes(query) || email.includes(query) || idNum.includes(query);
    }
    
    return true;
  });

  const stats = [
    { label: 'System Inventory', value: books.length, icon: BookIcon, color: 'blue', trend: 'Records' },
    { label: 'Available Assets', value: books.filter(b => b.available_copies > 0).length, icon: CheckCircle2, color: 'emerald', trend: 'Live' },
    { label: 'Pending Requests', value: reservations.filter(r => r.status === 'pending').length, icon: CalendarClock, color: 'purple', trend: 'Queue' },
    { label: 'Active Fines', value: fines.filter(f => f.status === 'unpaid').length, icon: HandCoins, color: 'rose', trend: 'Unpaid' },
  ];

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      case 'purple': return 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800';
      case 'rose': return 'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Knowledge Repository</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Library Management</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => exportToCsv(
              `library_catalog_${new Date().toISOString().split('T')[0]}.csv`,
              filtered.map(b => ({
                id: b.id,
                isbn: b.isbn ?? '',
                title: b.title ?? '',
                author: b.author ?? '',
                category: b.category ?? '',
                publisher: b.publisher ?? '',
                year_published: b.year_published ?? '',
                total_copies: b.total_copies,
                available_copies: b.available_copies,
                shelf_location: b.shelf_location ?? ''
              }))
            )}
            className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
          >
            <Download size={18} className="text-primary" />
            Export Catalog
          </button>
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={() => {
                setEditingBook(null);
                setForm({ isbn: '', title: '', author: '', category: '', publisher: '', year_published: '', total_copies: 1, shelf_location: '' });
                setShowModal(true);
            }}
          >
            <Plus size={18} />
            Add New Resource
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-grow lg:flex-grow-0 min-w-0 overflow-x-auto no-scrollbar">
          {[
            { id: 'books', label: 'Asset Catalog', icon: LibraryIcon },
            { id: 'issues', label: 'Circulation', icon: Clock },
            { id: 'reservations', label: 'Requests', icon: CalendarClock },
            { id: 'fines', label: 'Penalties', icon: HandCoins },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                flex-1 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap flex items-center justify-center gap-2
                ${activeTab === tab.id 
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                  : 'text-text-muted hover:text-text'}
              `}
            >
              <tab.icon size={14} />
              {tab.label}
            </button>
          ))}
        </div>

        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
            placeholder="Search catalog, issues, requests..."
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
      </div>

      {/* Main Content Area */}
      {loading ? (
        <div className="py-20 text-center">
          <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing Knowledge Base...</p>
        </div>
      ) : activeTab === 'books' ? (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
          {filteredBooks.length === 0 ? (
            <div className="col-span-full py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
              <BookOpen size={64} className="mx-auto text-text-muted/30 mb-6" />
              <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">Inventory Empty</h3>
              <p className="text-text-muted font-medium max-w-xs mx-auto">No matching assets identified in the library registry.</p>
            </div>
          ) : (
            filteredBooks.map((book) => (
              <div key={book.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden flex flex-col">
                <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/20 transition-colors"></div>
                
                <div className="relative z-10 space-y-6 flex-grow">
                    <div className="flex justify-between items-start">
                        <div className="w-14 h-14 rounded-2xl bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center border border-blue-100 dark:border-blue-800 shadow-sm group-hover:scale-110 transition-transform">
                            <Bookmark size={28} />
                        </div>
                        <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                            book.available_copies > 0 
                            ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' 
                            : 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800'
                        }`}>
                            {book.available_copies > 0 ? 'In Stock' : 'Reserved'}
                        </span>
                    </div>

                    <div className="space-y-1">
                        <h3 className="text-xl font-black text-text tracking-tight group-hover:text-primary transition-colors line-clamp-1">{book.title}</h3>
                        <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-[3px]">{book.author}</p>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                        <div className="bg-muted/50 dark:bg-muted/20 rounded-xl p-3 border border-border">
                            <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest mb-1 flex items-center gap-1.5"><Hash size={10} /> ISBN</p>
                            <p className="text-xs font-bold text-text truncate">{book.isbn || 'UNTRACKED'}</p>
                        </div>
                        <div className="bg-muted/50 dark:bg-muted/20 rounded-xl p-3 border border-border">
                            <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest mb-1 flex items-center gap-1.5"><MapPin size={10} /> Shelf Loc</p>
                            <p className="text-xs font-bold text-text">{book.shelf_location || 'GEN-01'}</p>
                        </div>
                    </div>

                    <div className="flex items-center gap-4 text-text-muted/50">
                        <div className="flex items-center gap-1.5 text-[0.65rem] font-black uppercase tracking-widest">
                            <LibraryIcon size={14} /> {book.category}
                        </div>
                        <div className="w-1 h-1 rounded-full bg-border"></div>
                        <div className="flex items-center gap-1.5 text-[0.65rem] font-black uppercase tracking-widest">
                            <BookOpen size={14} /> {book.available_copies}/{book.total_copies} Units
                        </div>
                    </div>
                </div>

                <div className="mt-8 pt-6 border-t border-border flex flex-wrap gap-2">
                    <button 
                        onClick={() => {
                            setEditingBook(book);
                            setForm({
                                isbn: book.isbn || '', title: book.title || '', author: book.author || '',
                                category: book.category || '', publisher: book.publisher || '',
                                year_published: book.year_published?.toString() || '',
                                total_copies: book.total_copies || 1, shelf_location: book.shelf_location || ''
                            });
                            setShowModal(true);
                        }}
                        className="flex-1 py-3 bg-muted dark:bg-muted/50 hover:bg-muted/80 text-text rounded-xl font-bold text-[0.65rem] uppercase tracking-widest transition-all border border-border flex items-center justify-center gap-2"
                    >
                        <Edit2 size={14} /> Update
                    </button>
                    <button 
                        onClick={() => openIssueModal(book)}
                        className="flex-1 py-3 bg-primary text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg flex items-center justify-center gap-2"
                    >
                        <BookmarkPlus size={16} /> Issue
                    </button>
                    <button 
                        onClick={async () => {
                            if (!window.confirm(`Delete record for "${book.title}"?`)) return;
                            await deleteBook(book.id);
                        }}
                        className="p-3 bg-rose-50 text-rose-600 rounded-xl hover:bg-rose-100 border border-rose-100 transition-all"
                    >
                        <Trash2 size={16} />
                    </button>
                </div>
              </div>
            ))
          )}
        </div>
      ) : activeTab === 'issues' ? (
        <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
                <table className="w-full text-left">
                    <thead>
                        <tr className="bg-muted/80 border-b border-border">
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Resource & Borrower</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Protocol Status</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Return Target</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                        {filteredIssues.length === 0 ? (
                            <tr>
                                <td colSpan={4} className="py-24 text-center">
                                    <Clock size={40} className="mx-auto text-text-muted/20 mb-4" />
                                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No active circulations</p>
                                </td>
                            </tr>
                        ) : (
                            filteredIssues.map((issue) => (
                                <tr key={issue.id} className="hover:bg-muted/30 transition-colors">
                                    <td className="px-8 py-5">
                                        <div className="flex items-center gap-4">
                                            <div className="w-10 h-10 rounded-xl bg-muted dark:bg-muted/20 flex items-center justify-center text-text-muted border border-border">
                                                <BookIcon size={18} />
                                            </div>
                                            <div>
                                                <p className="text-sm font-bold text-text">{issue.book_title}</p>
                                                <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">Borrower: {issue.first_name} {issue.last_name}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5">
                                        <span className={`px-3 py-1 text-[0.6rem] font-black rounded-lg uppercase tracking-widest border ${
                                          issue.status === 'returned' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 'bg-orange-50 text-orange-600 border-orange-100'
                                        }`}>
                                            {issue.status}
                                        </span>
                                    </td>
                                    <td className="px-8 py-5">
                                        <div className="flex items-center gap-2 text-text-muted font-bold font-mono text-xs">
                                            <Clock size={14} className="opacity-50" />
                                            {issue.due_date}
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        {issue.status === 'issued' && (
                                          <button 
                                              onClick={() => openReturnModal(issue)}
                                              className="px-6 py-2.5 bg-emerald-600 text-white rounded-xl font-black text-[0.6rem] uppercase tracking-widest hover:bg-emerald-700 transition-all shadow-md active:scale-95"
                                          >
                                              Process Return
                                          </button>
                                        )}
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
      ) : activeTab === 'reservations' ? (
        <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
                <table className="w-full text-left">
                    <thead>
                        <tr className="bg-muted/80 border-b border-border">
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Resource</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Requester</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Status</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                        {filteredReservations.length === 0 ? (
                            <tr>
                                <td colSpan={4} className="py-24 text-center">
                                    <CalendarClock size={40} className="mx-auto text-text-muted/20 mb-4" />
                                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No pending requests</p>
                                </td>
                            </tr>
                        ) : (
                            filteredReservations.map((res) => (
                                <tr key={res.id} className="hover:bg-muted/30 transition-colors">
                                    <td className="px-8 py-5">
                                        <p className="text-sm font-bold text-text">{res.book_title}</p>
                                        <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">{res.book_author}</p>
                                    </td>
                                    <td className="px-8 py-5">
                                        <p className="text-xs font-bold text-text">{res.first_name} {res.last_name}</p>
                                        <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">Date: {res.reservation_date}</p>
                                    </td>
                                    <td className="px-8 py-5">
                                        <span className={`px-3 py-1 text-[0.6rem] font-black rounded-lg uppercase tracking-widest border ${
                                          res.status === 'pending' ? 'bg-orange-50 text-orange-600 border-orange-100' :
                                          res.status === 'fulfilled' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' :
                                          'bg-rose-50 text-rose-600 border-rose-100'
                                        }`}>
                                            {res.status}
                                        </span>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        {res.status === 'pending' && (
                                          <button 
                                              onClick={() => cancelReservation(res.id)}
                                              className="p-2 text-rose-500 hover:bg-rose-50 rounded-lg transition-all"
                                          >
                                              <X size={18} />
                                          </button>
                                        )}
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
      ) : (
        <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
                <table className="w-full text-left">
                    <thead>
                        <tr className="bg-muted/80 border-b border-border">
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Offender</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Reason / Resource</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Amount</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Status</th>
                            <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                        {filteredFines.length === 0 ? (
                            <tr>
                                <td colSpan={5} className="py-24 text-center">
                                    <HandCoins size={40} className="mx-auto text-text-muted/20 mb-4" />
                                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">No active penalties</p>
                                </td>
                            </tr>
                        ) : (
                            filteredFines.map((fine) => (
                                <tr key={fine.id} className="hover:bg-muted/30 transition-colors">
                                    <td className="px-8 py-5">
                                        <p className="text-xs font-bold text-text">{fine.first_name} {fine.last_name}</p>
                                    </td>
                                    <td className="px-8 py-5">
                                        <p className="text-sm font-bold text-text">{fine.reason}</p>
                                        <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">{fine.book_title}</p>
                                    </td>
                                    <td className="px-8 py-5 text-rose-500 font-black">
                                        ${fine.amount.toFixed(2)}
                                    </td>
                                    <td className="px-8 py-5">
                                        <span className={`px-3 py-1 text-[0.6rem] font-black rounded-lg uppercase tracking-widest border ${
                                          fine.status === 'paid' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' :
                                          fine.status === 'unpaid' ? 'bg-rose-50 text-rose-600 border-rose-100' :
                                          'bg-blue-50 text-blue-600 border-blue-100'
                                        }`}>
                                            {fine.status}
                                        </span>
                                    </td>
                                    <td className="px-8 py-5 text-right flex gap-2 justify-end">
                                        {fine.status === 'unpaid' && (
                                          <>
                                            <button 
                                                onClick={() => payFine(fine.id)}
                                                className="px-4 py-2 bg-emerald-600 text-white rounded-lg font-black text-[0.6rem] uppercase tracking-widest hover:bg-emerald-700 transition-all shadow-md active:scale-95"
                                            >
                                                Mark Paid
                                            </button>
                                            <button 
                                                onClick={() => waiveFine(fine.id)}
                                                className="px-4 py-2 bg-muted text-text rounded-lg font-black text-[0.6rem] uppercase tracking-widest transition-all"
                                            >
                                                Waive
                                            </button>
                                          </>
                                        )}
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
      )}

      {/* Modal Infrastructure */}
      {showModal && (
        <Modal
          open={true}
          onClose={() => setShowModal(false)}
          title={editingBook ? 'Update Book' : 'Register New Resource'}
          maxWidth="max-w-2xl"
          zIndex={150}
        >
          <ModalBody>

            <div className="p-10 space-y-6 overflow-y-auto custom-scrollbar">
                <div className="grid grid-cols-2 gap-6">
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">ISBN Identifier</label>
                        <input className="form-input text-text" value={form.isbn} onChange={e => setForm({ ...form, isbn: e.target.value })} placeholder="e.g., 978-3-16-148410-0" />
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Subject Division</label>
                        <select className="form-input appearance-none text-text" value={form.category} onChange={e => setForm({ ...form, category: e.target.value })}>
                            <option value="">Select Genre...</option>
                            <option value="Sciences">Sciences</option>
                            <option value="Mathematics">Mathematics</option>
                            <option value="Humanities">Humanities</option>
                            <option value="Languages">Languages</option>
                            <option value="Technology">Technology</option>
                            <option value="Reference">Reference</option>
                        </select>
                    </div>
                </div>

                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Resource Title</label>
                    <input className="form-input text-text" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="Enter the official book title" />
                </div>

                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Primary Author</label>
                    <input className="form-input text-text" value={form.author} onChange={e => setForm({ ...form, author: e.target.value })} placeholder="Academic author name" />
                </div>

                <div className="grid grid-cols-3 gap-6">
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Pub Year</label>
                        <input className="form-input text-text" value={form.year_published} onChange={e => setForm({ ...form, year_published: e.target.value })} placeholder="YYYY" />
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Units</label>
                        <input type="number" className="form-input text-text" value={form.total_copies} onChange={e => setForm({ ...form, total_copies: Number(e.target.value) })} />
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Shelf Loc</label>
                        <input className="form-input text-text" value={form.shelf_location} onChange={e => setForm({ ...form, shelf_location: e.target.value })} placeholder="A-101" />
                    </div>
                </div>

                <div className="pt-4 flex gap-4">
                    <button onClick={() => setShowModal(false)} className="flex-1 py-4 bg-muted/50 hover:bg-muted text-text font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all border border-border">Cancel</button>
                    <button onClick={saveBook} className="flex-1 py-4 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-2">
                        {editingBook ? <CheckCircle2 size={16} /> : <Plus size={16} />}
                        {editingBook ? 'Commit Update' : 'Finalize Entry'}
                    </button>
                </div>
            </div>
          </ModalBody>
        </Modal>
      )}

      {/* Issue Asset Modal */}
      {showIssueModal && selectedBookForIssue && (
        <Modal
          open={true}
          onClose={() => setShowIssueModal(false)}
          title="Circulate Asset"
          maxWidth="max-w-lg"
          zIndex={150}
        >
          <ModalBody>

            <div className="p-10 space-y-6 overflow-y-auto custom-scrollbar">
              <div className="bg-muted/30 border border-border rounded-2xl p-4 flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center border border-blue-100 dark:border-blue-800"><BookIcon size={20} /></div>
                <div>
                  <p className="text-xs font-black text-text uppercase tracking-wider">{selectedBookForIssue.title}</p>
                  <p className="text-[0.6rem] text-text-muted font-bold uppercase tracking-widest">{selectedBookForIssue.author} • {selectedBookForIssue.available_copies} available</p>
                </div>
              </div>

              <div className="space-y-1.5 relative" ref={dropdownRef}>
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Borrower (Student / Teacher)</label>
                <div className="relative">
                  <input 
                      className="form-input text-text pl-10 pr-4" 
                      value={userSearch} 
                      onChange={e => {
                        setUserSearch(e.target.value);
                        setSelectedUser(null);
                        setShowUserDropdown(true);
                      }}
                      onFocus={() => setShowUserDropdown(true)}
                      placeholder="Select or search borrower..."
                      required
                  />
                  <Search size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" />
                  {selectedUser && (
                    <CheckCircle2 size={16} className="absolute right-3.5 top-1/2 -translate-y-1/2 text-emerald-500" />
                  )}
                </div>
                
                {showUserDropdown && (
                  <div className="absolute z-20 top-full left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-xl flex flex-col max-h-64 overflow-hidden animate-in slide-in-from-top-2 duration-150">
                    <div className="flex border-b border-border bg-muted/30 p-1 shrink-0">
                      {[
                        { id: 'all', label: 'All Roles' },
                        { id: 'student', label: 'Students' },
                        { id: 'teacher', label: 'Teachers' }
                      ].map(tab => (
                        <button
                          key={tab.id}
                          type="button"
                          onClick={() => setBorrowerRoleFilter(tab.id as any)}
                          className={`flex-1 py-1.5 rounded-lg text-[0.6rem] font-black uppercase tracking-wider transition-all ${
                            borrowerRoleFilter === tab.id
                              ? 'bg-card text-primary shadow-sm border border-border'
                              : 'text-text-muted hover:text-text'
                          }`}
                        >
                          {tab.label}
                        </button>
                      ))}
                    </div>

                    <div className="overflow-y-auto divide-y divide-border/50 custom-scrollbar flex-1">
                      {filteredUsersForIssue.length === 0 ? (
                        <div className="p-4 text-xs text-text-muted text-center">No members found</div>
                      ) : (
                        filteredUsersForIssue.map(u => (
                          <button
                            key={u.id}
                            type="button"
                            onClick={() => {
                              setSelectedUser(u);
                              setUserSearch(`${u.first_name} ${u.last_name} (${u.role.toUpperCase()})`);
                              setShowUserDropdown(false);
                            }}
                            className="w-full px-5 py-3 text-left hover:bg-muted/50 transition-colors flex items-center justify-between"
                          >
                            <div>
                              <p className="text-xs font-bold text-text">{u.first_name} {u.last_name}</p>
                              <p className="text-[0.6rem] text-text-muted uppercase tracking-wider">{u.email} • {u.role}</p>
                            </div>
                            <span className="text-[0.6rem] font-bold text-text-muted px-2.5 py-1 bg-muted border border-border rounded-lg uppercase">{u.id_number || `ID: ${u.id}`}</span>
                          </button>
                        ))
                      )}
                    </div>
                  </div>
                )}
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Due Date Target</label>
                <input 
                    type="date"
                    className="form-input text-text" 
                    value={issueDueDate} 
                    onChange={e => setIssueDueDate(e.target.value)} 
                    required 
                />
              </div>

              <div className="pt-4 flex gap-4">
                <button type="button" onClick={() => setShowIssueModal(false)} className="flex-1 py-4 bg-muted/50 hover:bg-muted text-text font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all border border-border">Abort</button>
                <button type="button" onClick={handleIssueBook} className="flex-1 py-4 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-2">
                  <BookmarkPlus size={16} /> Initiate Circulation
                </button>
              </div>
            </div>
          </ModalBody>
        </Modal>
      )}

      {/* Return Asset Modal */}
      {showReturnModal && selectedIssueForReturn && (
        <Modal
          open={true}
          onClose={() => setShowReturnModal(false)}
          title="Finalize Circulation"
          maxWidth="max-w-lg"
          zIndex={150}
        >
          <ModalBody>

            <div className="p-10 space-y-6 overflow-y-auto custom-scrollbar">
              <div className="bg-muted/30 border border-border rounded-2xl p-4 space-y-2">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 flex items-center justify-center border border-emerald-100 dark:border-emerald-800"><CheckCircle2 size={20} /></div>
                  <div>
                    <p className="text-xs font-black text-text uppercase tracking-wider">{selectedIssueForReturn.book_title}</p>
                    <p className="text-[0.6rem] text-text-muted font-bold uppercase tracking-widest">Borrower: {selectedIssueForReturn.first_name} {selectedIssueForReturn.last_name}</p>
                  </div>
                </div>
                <div className="border-t border-border/50 pt-2 flex justify-between text-[0.65rem] font-bold text-text-muted uppercase tracking-wider">
                  <span>Issued: {selectedIssueForReturn.issue_date}</span>
                  <span>Target Due: {selectedIssueForReturn.due_date}</span>
                </div>
              </div>

              <div className="flex items-center gap-3 p-5 bg-rose-50 dark:bg-rose-900/20 rounded-2xl border border-rose-100 dark:border-rose-800">
                <div className="w-10 h-10 rounded-xl bg-card border border-border flex items-center justify-center text-rose-600 dark:text-rose-400 shadow-sm"><HandCoins size={20} /></div>
                <div className="flex-1">
                  <p className="text-[0.65rem] font-black uppercase text-rose-600 dark:text-rose-400 tracking-widest">Apply Penalty Fine</p>
                  <p className="text-[0.6rem] font-bold text-rose-400 dark:text-rose-300">Generate fine record for overdue or damage</p>
                </div>
                <input 
                    type="checkbox" 
                    className="w-6 h-6 rounded-lg border-rose-200 dark:border-rose-700 text-rose-600 focus:ring-rose-500 cursor-pointer"
                    checked={returnFineChecked}
                    onChange={e => setReturnFineChecked(e.target.checked)}
                />
              </div>

              <div className="space-y-4">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Quick Presets</label>
                <div className="grid grid-cols-4 gap-2">
                  <button type="button" onClick={() => applyReturnPreset(0, '')} className={`py-2.5 text-[0.6rem] font-black uppercase border rounded-xl transition-all ${!returnFineChecked ? 'bg-primary/10 border-primary text-primary shadow-sm' : 'bg-card border-border text-text-muted hover:bg-muted/50'}`}>No Fine</button>
                  <button type="button" onClick={() => applyReturnPreset(5, 'Late Return')} className={`py-2.5 text-[0.6rem] font-black uppercase border rounded-xl transition-all ${returnFineChecked && returnFineAmount === 5 ? 'bg-amber-500/10 border-amber-500 text-amber-600 dark:text-amber-400 shadow-sm' : 'bg-card border-border text-text-muted hover:bg-muted/50'}`}>Late ($5)</button>
                  <button type="button" onClick={() => applyReturnPreset(15, 'Book Damaged')} className={`py-2.5 text-[0.6rem] font-black uppercase border rounded-xl transition-all ${returnFineChecked && returnFineAmount === 15 ? 'bg-rose-500/10 border-rose-500 text-rose-600 dark:text-rose-400 shadow-sm' : 'bg-card border-border text-text-muted hover:bg-muted/50'}`}>Damage ($15)</button>
                  <button type="button" onClick={() => applyReturnPreset(25, 'Book Lost')} className={`py-2.5 text-[0.6rem] font-black uppercase border rounded-xl transition-all ${returnFineChecked && returnFineAmount === 25 ? 'bg-rose-500/10 border-rose-500 text-rose-600 dark:text-rose-400 shadow-sm' : 'bg-card border-border text-text-muted hover:bg-muted/50'}`}>Lost ($25)</button>
                </div>
              </div>

              {returnFineChecked && (
                <div className="grid grid-cols-2 gap-4 animate-in slide-in-from-top-4 duration-200">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Fine Amount ($)</label>
                    <input 
                        type="number" 
                        min="0"
                        step="0.01"
                        className="form-input text-text" 
                        value={returnFineAmount} 
                        onChange={e => setReturnFineAmount(Number(e.target.value))} 
                        required 
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Fine Reason</label>
                    <input 
                        className="form-input text-text" 
                        value={returnFineReason} 
                        onChange={e => setReturnFineReason(e.target.value)} 
                        placeholder="e.g., Cover Torn" 
                        required 
                    />
                  </div>
                </div>
              )}

              <div className="pt-4 flex gap-4">
                <button type="button" onClick={() => setShowReturnModal(false)} className="flex-1 py-4 bg-muted/50 hover:bg-muted text-text font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all border border-border">Abort</button>
                <button type="button" onClick={handleReturnBook} className="flex-1 py-4 bg-emerald-600 hover:bg-emerald-700 text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-2">
                  <CheckCircle2 size={16} /> Complete Return
                </button>
              </div>
            </div>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}
