import { useState, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { 
  History, Search, Plus, User, Book, 
  Calendar, Clock, CheckCircle2, AlertCircle,
  X, Filter, MoreVertical, LogOut,
  ArrowRight, CreditCard, ShieldAlert
} from 'lucide-react';
import api from '../../store/auth';

interface LibraryIssue {
  id: number;
  uid: string;
  book_id: number;
  book_title: string;
  book_author: string;
  user_id: number;
  first_name: string;
  last_name: string;
  issue_date: string;
  due_date: string;
  return_date: string | null;
  status: 'issued' | 'returned' | 'lost';
  issuer_name: string;
}

export default function IssueManagement() {
  const [issues, setIssues] = useState<LibraryIssue[]>([]);
  const [books, setBooks] = useState<any[]>([]);
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showIssueModal, setShowIssueModal] = useState(false);
  const [showReturnModal, setShowReturnModal] = useState<LibraryIssue | null>(null);
  
  const [formData, setFormData] = useState({
    book_id: '',
    user_id: '',
    due_date: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  });

  const [bookSearch, setBookSearch] = useState('');
  const [memberSearch, setMemberSearch] = useState('');
  const [showBookDropdown, setShowBookDropdown] = useState(false);
  const [showMemberDropdown, setShowMemberDropdown] = useState(false);

  const bookDropdownRef = useRef<HTMLDivElement>(null);
  const memberDropdownRef = useRef<HTMLDivElement>(null);

  const filteredBooks = books.filter(b => {
    if (b.available_copies <= 0) return false;
    const title = b.title.toLowerCase();
    const author = (b.author || '').toLowerCase();
    const query = bookSearch.toLowerCase();
    return title.includes(query) || author.includes(query);
  });

  const filteredUsers = users.filter(u => {
    const fullName = `${u.first_name} ${u.last_name}`.toLowerCase();
    const email = (u.email || '').toLowerCase();
    const role = (u.role || '').toLowerCase();
    const query = memberSearch.toLowerCase();
    return fullName.includes(query) || email.includes(query) || role.includes(query);
  });

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

  useEffect(() => {
    if (books.length > 0 && users.length > 0) {
      const queryParams = new URLSearchParams(window.location.search);
      const preselectedBookId = queryParams.get('book_id');
      const preselectedUserId = queryParams.get('user_id');
      const autoOpen = queryParams.get('action') === 'new';

      let hasPreselected = false;
      let newBookId = '';
      let newBookSearch = '';
      let newUserId = '';
      let newMemberSearch = '';

      if (preselectedBookId) {
        const book = books.find(b => b.id === parseInt(preselectedBookId));
        if (book) {
          newBookId = String(book.id);
          newBookSearch = `${book.title} (${book.available_copies} available)`;
          hasPreselected = true;
        }
      }

      if (preselectedUserId) {
        const user = users.find(u => u.id === parseInt(preselectedUserId));
        if (user) {
          newUserId = String(user.id);
          const roleStr = user.role ? ` [${user.role.replace('_', ' ')}]` : '';
          newMemberSearch = `${user.first_name} ${user.last_name}${roleStr}`;
          hasPreselected = true;
        }
      }

      if (hasPreselected) {
        setFormData(prev => ({
          ...prev,
          book_id: newBookId || prev.book_id,
          user_id: newUserId || prev.user_id
        }));
        if (newBookSearch) setBookSearch(newBookSearch);
        if (newMemberSearch) setMemberSearch(newMemberSearch);
        setShowIssueModal(true);
        window.history.replaceState({}, document.title, window.location.pathname);
      } else if (autoOpen) {
        setShowIssueModal(true);
        window.history.replaceState({}, document.title, window.location.pathname);
      }
    }
  }, [books, users]);

  const [returnFormData, setReturnFormData] = useState({
    condition_notes: '',
    generate_fine: false,
    fine_amount: 0,
    fine_reason: 'Overdue',
    is_lost: false
  });

  const fetchData = async () => {
    try {
      setLoading(true);
      const [issuesRes, booksRes, usersRes] = await Promise.all([
        api.get('/library/issues'),
        api.get('/library/books'),
        api.get('/users?limit=1000')
      ]);
      setIssues(issuesRes.data);
      setBooks(booksRes.data);
      const userData = usersRes.data.users || usersRes.data;
      setUsers(Array.isArray(userData) ? userData : []);
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleIssue = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.book_id || !formData.user_id) {
      alert('Please select a book and a member from the search dropdown lists.');
      return;
    }
    try {
      await api.post('/library/issues', formData);
      setShowIssueModal(false);
      setFormData({
        book_id: '',
        user_id: '',
        due_date: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
      });
      setBookSearch('');
      setMemberSearch('');
      fetchData();
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Failed to issue book');
    }
  };

  const handleReturn = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!showReturnModal) return;
    try {
      await api.put(`/library/issues/${showReturnModal.id}/return`, returnFormData);
      setShowReturnModal(null);
      setReturnFormData({
        condition_notes: '',
        generate_fine: false,
        fine_amount: 0,
        fine_reason: 'Overdue',
        is_lost: false
      });
      fetchData();
    } catch (error) {
      console.error('Error returning book:', error);
    }
  };

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

  const getStatusStyle = (issue: LibraryIssue) => {
    if (issue.status === 'returned') {
      return 'bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30';
    }
    const isOverdue = new Date(issue.due_date) < new Date();
    if (isOverdue) {
      return 'bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-900/30 animate-pulse';
    }
    return 'bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400 border-blue-100 dark:border-blue-900/30';
  };

  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">
            <History className="text-primary" />
            Book Borrowing
          </h1>
          <p className="text-text-muted text-sm mt-1">Manage issues, returns and track overdues</p>
        </div>
        <button
          onClick={() => {
            setFormData({
              book_id: '',
              user_id: '',
              due_date: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
            });
            setBookSearch('');
            setMemberSearch('');
            setShowBookDropdown(false);
            setShowMemberDropdown(false);
            setShowIssueModal(true);
          }}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:opacity-90 transition-all shadow-sm font-semibold"
        >
          <Plus size={20} />
          New Issue
        </button>
      </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 book or member name..."
              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>Borrowed By</th>
                <th>Timeline</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>
              ) : filteredIssues.length === 0 ? (
                <tr><td colSpan={5} className="px-6 py-12 text-center text-text-muted">No issue records found</td></tr>
              ) : (
                filteredIssues.map((issue) => (
                  <tr key={issue.id} className="ng-table-row">
                    <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">{issue.book_title}</p>
                          <p className="text-[0.7rem] text-text-muted truncate max-w-[150px]">{issue.book_author}</p>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell font-medium">
                      {issue.first_name} {issue.last_name}
                    </td>
                    <td className="ng-table-cell">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-[0.7rem] text-text-muted">
                          <Clock size={12} className="text-primary" aria-hidden="true" />
                          <span>Issued: {new Date(issue.issue_date).toLocaleDateString()}</span>
                        </div>
                        <div className="flex items-center gap-2 text-[0.7rem] font-semibold">
                          <Calendar size={12} className={new Date(issue.due_date) < new Date() && issue.status !== 'returned' ? 'text-red-500 dark:text-red-400' : 'text-amber-500 dark:text-amber-400'} aria-hidden="true" />
                          <span className={new Date(issue.due_date) < new Date() && issue.status !== 'returned' ? 'text-red-600 dark:text-red-400' : 'text-amber-600 dark:text-amber-400'}>
                            Due: {new Date(issue.due_date).toLocaleDateString()}
                          </span>
                        </div>
                        {issue.return_date && (
                          <div className="flex items-center gap-2 text-[0.7rem] text-emerald-600 dark:text-emerald-400 font-bold">
                            <CheckCircle2 size={12} aria-hidden="true" />
                            <span>Returned: {new Date(issue.return_date).toLocaleDateString()}</span>
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <span className={`ng-table-badge ${getStatusStyle(issue)}`}>
                        {issue.status === 'issued' && new Date(issue.due_date) < new Date() ? 'OVERDUE' : issue.status}
                      </span>
                    </td>
                    <td className="ng-table-cell text-right">
                      {issue.status === 'issued' && (
                        <button
                          onClick={() => setShowReturnModal(issue)}
                          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 ml-auto shadow-sm cursor-pointer"
                        >
                          <LogOut size={14} className="rotate-180" aria-hidden="true" />
                          Return
                        </button>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* New Issue Modal */}
      {showIssueModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4" onClick={() => setShowIssueModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <Book size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Issue Book</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Lend a book to a campus member</p>
              </div>
              <button 
                type="button" 
                onClick={() => setShowIssueModal(false)} 
                className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleIssue} className="p-10 space-y-6">
              <div className="space-y-1.5 relative" ref={bookDropdownRef}>
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Book*</label>
                <div className="relative group">
                  <Book size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                  <input
                    required
                    type="text"
                    className="form-input pl-11 text-text pr-10 cursor-pointer"
                    placeholder="Type book title or author to search..."
                    value={bookSearch}
                    onChange={e => {
                      setBookSearch(e.target.value);
                      setShowBookDropdown(true);
                      if (formData.book_id) {
                        setFormData({ ...formData, book_id: '' });
                      }
                    }}
                    onFocus={() => {
                      setShowBookDropdown(true);
                      if (!formData.book_id) {
                        setBookSearch('');
                      }
                    }}
                  />
                  {formData.book_id && (
                    <button 
                      type="button"
                      onClick={() => {
                        setFormData({ ...formData, book_id: '' });
                        setBookSearch('');
                        setShowBookDropdown(true);
                      }}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500"
                    >
                      <X size={16} />
                    </button>
                  )}
                </div>

                {showBookDropdown && (
                  <div className="absolute z-[160] left-0 right-0 mt-1 max-h-60 overflow-y-auto bg-card border border-border rounded-2xl shadow-xl animate-in fade-in slide-in-from-top-2 duration-200 custom-scrollbar">
                    {filteredBooks.length === 0 ? (
                      <div className="p-4 text-center text-text-muted text-xs font-bold uppercase tracking-widest">
                        No books found
                      </div>
                    ) : (
                      filteredBooks.map(b => (
                        <div
                          key={b.id}
                          onClick={() => {
                            setFormData({ ...formData, book_id: String(b.id) });
                            setBookSearch(`${b.title} (${b.available_copies} available)`);
                            setShowBookDropdown(false);
                          }}
                          className={`px-4 py-3 cursor-pointer text-sm font-bold text-text hover:bg-primary/5 transition-colors border-b border-border/50 last:border-0 flex flex-col ${formData.book_id === String(b.id) ? 'bg-primary/5 text-primary' : ''}`}
                        >
                          <span>{b.title}</span>
                          <span className="text-[0.65rem] text-text-muted dark:text-text-secondary font-medium mt-0.5">Author: {b.author} | Shelf: {b.shelf_location || 'N/A'}</span>
                        </div>
                      ))
                    )}
                  </div>
                )}
              </div>

              <div className="space-y-1.5 relative" ref={memberDropdownRef}>
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Member*</label>
                <div className="relative group">
                  <User size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                  <input
                    required
                    type="text"
                    className="form-input pl-11 text-text pr-10 cursor-pointer"
                    placeholder="Type member name, email, or role to search..."
                    value={memberSearch}
                    onChange={e => {
                      setMemberSearch(e.target.value);
                      setShowMemberDropdown(true);
                      if (formData.user_id) {
                        setFormData({ ...formData, user_id: '' });
                      }
                    }}
                    onFocus={() => {
                      setShowMemberDropdown(true);
                      if (!formData.user_id) {
                        setMemberSearch('');
                      }
                    }}
                  />
                  {formData.user_id && (
                    <button 
                      type="button"
                      onClick={() => {
                        setFormData({ ...formData, user_id: '' });
                        setMemberSearch('');
                        setShowMemberDropdown(true);
                      }}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500"
                    >
                      <X size={16} />
                    </button>
                  )}
                </div>

                {showMemberDropdown && (
                  <div className="absolute z-[160] left-0 right-0 mt-1 max-h-60 overflow-y-auto bg-card border border-border rounded-2xl shadow-xl animate-in fade-in slide-in-from-top-2 duration-200 custom-scrollbar">
                    {filteredUsers.length === 0 ? (
                      <div className="p-4 text-center text-text-muted text-xs font-bold uppercase tracking-widest">
                        No members found
                      </div>
                    ) : (
                      filteredUsers.map(u => (
                        <div
                          key={u.id}
                          onClick={() => {
                            setFormData({ ...formData, user_id: String(u.id) });
                            setMemberSearch(`${u.first_name} ${u.last_name} [${u.role.replace('_', ' ')}]`);
                            setShowMemberDropdown(false);
                          }}
                          className={`px-4 py-3 cursor-pointer text-sm font-bold text-text hover:bg-primary/5 transition-colors border-b border-border/50 last:border-0 flex flex-col ${formData.user_id === String(u.id) ? 'bg-primary/5 text-primary' : ''}`}
                        >
                          <span>{u.first_name} {u.last_name}</span>
                          <span className="text-[0.65rem] text-text-muted dark:text-text-secondary font-medium mt-0.5">Email: {u.email} | Role: <span className="capitalize">{u.role.replace('_', ' ')}</span></span>
                        </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*</label>
                <div className="relative group">
                  <Calendar size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                  <input
                    required
                    type="date"
                    value={formData.due_date}
                    onChange={e => setFormData({ ...formData, due_date: e.target.value })}
                    className="form-input pl-11 text-text pr-4"
                  />
                </div>
              </div>

              <div className="mt-8 pt-6 border-t border-border flex items-center justify-end gap-4">
                <button 
                  type="button" 
                  onClick={() => setShowIssueModal(false)} 
                  className="flex-1 py-4 bg-muted rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:bg-muted/80 text-text-muted"
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  className="flex-1 py-4 bg-primary text-white rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:opacity-90 shadow-lg shadow-primary/20"
                >
                  Confirm Issue
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Return Modal */}
      {showReturnModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4" onClick={() => setShowReturnModal(null)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-md shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-emerald-600 dark:text-emerald-400">
                <CheckCircle2 size={150} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Return Book</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Process a returned or lost book copy</p>
              </div>
              <button 
                type="button" 
                onClick={() => setShowReturnModal(null)} 
                className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm"
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleReturn} className="p-10 space-y-6">
              <div className="p-4 bg-background-alt rounded-2xl border border-border">
                <p className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest mb-1">Returning</p>
                <p className="font-bold text-text">{showReturnModal.book_title}</p>
                <p className="text-xs text-text-secondary mt-0.5">Member: {showReturnModal.first_name} {showReturnModal.last_name}</p>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Return Status*</label>
                <select
                  value={returnFormData.is_lost ? 'lost' : 'returned'}
                  onChange={e => {
                    const lost = e.target.value === 'lost';
                    setReturnFormData({
                      ...returnFormData,
                      is_lost: lost,
                      generate_fine: lost ? true : returnFormData.generate_fine,
                      fine_reason: lost ? 'Lost' : (returnFormData.fine_reason === 'Lost' ? 'Overdue' : returnFormData.fine_reason)
                    });
                  }}
                  className="w-full px-4 py-2.5 bg-background-alt border border-border rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-xs font-bold text-text"
                >
                  <option value="returned" className="bg-surface text-text">Returned</option>
                  <option value="lost" className="bg-surface text-text">Lost (Permanently)</option>
                </select>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Book Condition Notes</label>
                <textarea
                  rows={2}
                  value={returnFormData.condition_notes}
                  onChange={e => setReturnFormData({ ...returnFormData, condition_notes: e.target.value })}
                  className="w-full px-4 py-2 bg-background-alt border border-border rounded-xl focus:ring-2 focus:ring-primary/20 outline-none transition-all resize-none text-sm text-text"
                  placeholder="e.g. Good condition, slight damage to spine..."
                />
              </div>

              <div className="flex items-center gap-2.5 p-4 bg-amber-50 dark:bg-amber-900/10 rounded-2xl border border-amber-100 dark:border-amber-900/30">
                <input
                  type="checkbox"
                  id="generate_fine"
                  checked={returnFormData.generate_fine}
                  disabled={returnFormData.is_lost} // Force fine selection if lost
                  onChange={e => setReturnFormData({ ...returnFormData, generate_fine: e.target.checked })}
                  className="w-4 h-4 text-primary rounded border-border"
                />
                <label htmlFor="generate_fine" className="text-xs font-bold text-amber-900 dark:text-amber-300 cursor-pointer">Generate library fine?</label>
              </div>

              {returnFormData.generate_fine && (
                <div className="space-y-4 animate-in slide-in-from-top-2 duration-200">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Amount ($)</label>
                      <input
                        type="number"
                        step="0.01"
                        required
                        value={returnFormData.fine_amount}
                        onChange={e => setReturnFormData({ ...returnFormData, fine_amount: parseFloat(e.target.value) || 0 })}
                        className="w-full px-4 py-2.5 bg-background-alt border border-border rounded-xl outline-none text-xs text-text"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Reason</label>
                      <select
                        value={returnFormData.fine_reason}
                        disabled={returnFormData.is_lost} // Force Reason to "Lost" if book is lost
                        onChange={e => setReturnFormData({ ...returnFormData, fine_reason: e.target.value })}
                        className="w-full px-4 py-2.5 bg-background-alt border border-border rounded-xl outline-none text-xs text-text"
                      >
                        <option value="Overdue" className="bg-surface text-text">Overdue</option>
                        <option value="Damaged" className="bg-surface text-text">Damaged</option>
                        <option value="Lost" className="bg-surface text-text">Lost</option>
                        <option value="Other" className="bg-surface text-text">Other</option>
                      </select>
                    </div>
                  </div>
                </div>
              )}

              <div className="mt-8 pt-6 border-t border-border flex items-center justify-end gap-4">
                <button 
                  type="button" 
                  onClick={() => setShowReturnModal(null)} 
                  className="flex-1 py-4 bg-muted rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:bg-muted/80 text-text-muted"
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  className="flex-1 py-4 bg-emerald-600 text-white rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:opacity-90 shadow-lg shadow-emerald-500/20"
                >
                  Confirm
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}
    </div>
  );
}
