import { useState, useEffect } from 'react';
import { 
  Book, Search, Plus, User, FileText, 
  MapPin, Tag, Hash, MoreVertical, X,
  Trash2, Edit, CheckCircle2, AlertCircle,
  Archive, Layers, Bookmark, UploadCloud, Download
} from 'lucide-react';
import api from '../../store/auth';
import { Link } from 'react-router-dom';
import { Modal, ModalBody } from '../../components/ui/Modal';

interface LibraryBook {
  id: number;
  uid: string;
  isbn: string;
  title: string;
  author: string;
  category: string;
  publisher: string;
  year_published: number;
  total_copies: number;
  available_copies: number;
  shelf_location: string;
  status: 'available' | 'reserved' | 'maintenance' | 'lost';
}

export default function BookManagement() {
  const [books, setBooks] = useState<LibraryBook[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);
  const [showBulkModal, setShowBulkModal] = useState(false);
  const [bulkData, setBulkData] = useState('');
  const [bulkStatus, setBulkStatus] = useState<{success: number, failed: number, errors: any[]} | null>(null);
  const [editingBook, setEditingBook] = useState<LibraryBook | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    author: '',
    isbn: '',
    category: '',
    publisher: '',
    year_published: new Date().getFullYear(),
    total_copies: 1,
    shelf_location: ''
  });

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

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingBook) {
        await api.put(`/library/books/${editingBook.id}`, formData);
      } else {
        await api.post('/library/books', formData);
      }
      setShowAddModal(false);
      setEditingBook(null);
      setFormData({
        title: '',
        author: '',
        isbn: '',
        category: '',
        publisher: '',
        year_published: new Date().getFullYear(),
        total_copies: 1,
        shelf_location: ''
      });
      fetchBooks();
    } catch (error) {
      console.error('Error saving book:', error);
    }
  };

  const handleBulkUpload = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const rows = bulkData.trim().split('\n');
      if (rows.length < 2) throw new Error('Data must contain a header and at least one data row');
      
      const headers = rows[0].split(',').map(h => h.trim().toLowerCase());
      const booksToUpload = rows.slice(1).map(row => {
        const values = row.split(',').map(v => v.trim());
        const book: any = {};
        headers.forEach((header, index) => {
          book[header] = values[index];
        });
        return book;
      });

      const response = await api.post('/library/books/bulk', { books: booksToUpload });
      setBulkStatus(response.data);
      if (response.data.failed === 0) {
        setTimeout(() => {
          setShowBulkModal(false);
          setBulkData('');
          setBulkStatus(null);
          fetchBooks();
        }, 2000);
      }
    } catch (error: any) {
      alert(error.response?.data?.error || error.message || 'Failed to process bulk upload');
    }
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this book?')) return;
    try {
      await api.delete(`/library/books/${id}`);
      fetchBooks();
    } catch (error) {
      console.error('Error deleting book:', error);
    }
  };

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

  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">
            <Book className="text-primary" />
            Book Catalog
          </h1>
          <p className="text-text-muted text-sm mt-1">Manage and track library inventory</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => setShowBulkModal(true)}
            className="flex items-center justify-center gap-2 px-4 py-2 bg-surface border border-border text-text-secondary rounded-lg hover:bg-background-alt transition-colors shadow-sm font-semibold"
          >
            <UploadCloud size={20} />
            Bulk Upload
          </button>
          <button
            onClick={() => {
              setEditingBook(null);
              setFormData({
                title: '',
                author: '',
                isbn: '',
                category: '',
                publisher: '',
                year_published: new Date().getFullYear(),
                total_copies: 1,
                shelf_location: ''
              });
              setShowAddModal(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} />
            Add New Book
          </button>
        </div>
      </div>

      <div className="ng-table-container">
        <div className="p-4 border-b border-border flex flex-col md:flex-row gap-4 items-center justify-between 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 title, author or ISBN..."
              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 className="text-center w-12">#</th>
                <th>Book Details</th>
                <th>Classification</th>
                <th>Location</th>
                <th>Inventory</th>
                <th>Status</th>
                <th className="text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50">
              {loading ? (
                <tr>
                  <td colSpan={7} className="px-6 py-12 text-center text-text-muted">
                    <div className="flex flex-col items-center gap-2">
                      <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
                      <span>Loading catalog...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredBooks.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-12 text-center text-text-muted">
                    <Book size={48} className="mx-auto mb-4 opacity-20" aria-hidden="true" />
                    <p>No books found in the catalog</p>
                  </td>
                </tr>
              ) : (
                filteredBooks.map((book, idx) => (
                  <tr key={book.id} className="ng-table-row group">
                    <td className="ng-table-cell text-center text-text-muted font-medium">
                      {idx + 1}
                    </td>
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-14 rounded-md bg-primary-50 dark:bg-primary-900/20 border border-primary-100 dark:border-primary-900/30 flex items-center justify-center flex-shrink-0">
                          <Book size={18} className="text-primary-400" aria-hidden="true" />
                        </div>
                        <div className="min-w-0">
                          <p className="font-bold text-text truncate max-w-[200px]">{book.title}</p>
                          <div className="flex items-center gap-2 text-xs text-text-muted mt-1">
                            <span className="truncate">{book.author}</span>
                            <span className="text-border-light">•</span>
                            <span className="font-mono">{book.isbn}</span>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <div className="space-y-1">
                        <span className="inline-flex items-center px-2 py-0.5 rounded bg-background-alt text-text-secondary text-[0.65rem] font-bold uppercase">
                          {book.category}
                        </span>
                        <p className="text-[0.65rem] text-text-muted font-medium">{book.publisher}, {book.year_published}</p>
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-1.5 text-xs font-semibold text-text-secondary">
                        <MapPin size={12} className="text-primary" aria-hidden="true" />
                        {book.shelf_location}
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-3">
                        <div className="flex flex-col items-center p-2 bg-primary-50 dark:bg-primary-900/20 rounded-lg min-w-[50px]">
                          <span className="text-[0.6rem] text-primary-600 dark:text-primary-400 font-bold uppercase">Total</span>
                          <span className="text-sm font-black text-primary-900 dark:text-primary-100">{book.total_copies}</span>
                        </div>
                        <div className={`flex flex-col items-center p-2 rounded-lg min-w-[50px] ${book.available_copies > 0 ? 'bg-emerald-50 dark:bg-emerald-900/20' : 'bg-red-50 dark:bg-red-900/20'}`}>
                          <span className={`text-[0.6rem] font-bold uppercase ${book.available_copies > 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>Left</span>
                          <span className={`text-sm font-black ${book.available_copies > 0 ? 'text-emerald-900 dark:text-emerald-100' : 'text-red-900 dark:text-red-100'}`}>{book.available_copies}</span>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <span className={`ng-table-badge ${
                        book.available_copies > 0 
                          ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' 
                          : 'bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 border-amber-100 dark:border-amber-900/30'
                      }`}>
                        {book.available_copies > 0 ? 'Available' : 'Reserved/Out'}
                      </span>
                    </td>
                    <td className="ng-table-cell text-right">
                      <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        {book.available_copies > 0 && (
                          <Link
                            to={`/library/issues?book_id=${book.id}`}
                            className="p-1.5 text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-900/20 rounded-lg transition-colors cursor-pointer flex items-center justify-center"
                            title="Issue Book"
                          >
                            <Bookmark size={16} aria-hidden="true" />
                          </Link>
                        )}
                        <button
                          onClick={() => {
                            setEditingBook(book);
                            setFormData({
                              title: book.title,
                              author: book.author,
                              isbn: book.isbn,
                              category: book.category,
                              publisher: book.publisher,
                              year_published: book.year_published,
                              total_copies: book.total_copies,
                              shelf_location: book.shelf_location
                            });
                            setShowAddModal(true);
                          }}
                          className="p-1.5 text-primary hover:bg-primary-50 dark:hover:bg-primary-900/20 rounded-lg transition-colors cursor-pointer"
                          title="Edit Book"
                        >
                          <Edit size={16} aria-hidden="true" />
                        </button>
                        <button
                          onClick={() => handleDelete(book.id)}
                          className="p-1.5 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors cursor-pointer"
                          title="Delete Book"
                        >
                          <Trash2 size={16} aria-hidden="true" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add/Edit Modal */}
      {showAddModal && (
        <Modal
          open={true}
          onClose={() => setShowAddModal(false)}
          title={editingBook ? 'Edit Book' : 'Library Catalog'}
          icon={Book}
          maxWidth="max-w-2xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0 dark:bg-background/50">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Book size={180} />
              </div>
              <div className="relative z-10">
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                  {editingBook ? 'Update inventory registry record' : 'Add a book to the catalog'}
                </p>
              </div>
            </div>
            <form id="books-add-form" onSubmit={handleSubmit} className="p-10 space-y-6 overflow-y-auto custom-scrollbar">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Book Title*</label>
                    <input
                      required
                      type="text"
                      value={formData.title}
                      onChange={e => setFormData({ ...formData, title: e.target.value })}
                      className="form-input"
                      placeholder="e.g. Modern Physics"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Author Name*</label>
                    <input
                      required
                      type="text"
                      value={formData.author}
                      onChange={e => setFormData({ ...formData, author: e.target.value })}
                      className="form-input"
                      placeholder="Full name"
                    />
                  </div>
                  <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">ISBN</label>
                      <input
                        type="text"
                        value={formData.isbn}
                        onChange={e => setFormData({ ...formData, isbn: e.target.value })}
                        className="form-input"
                        placeholder="13-digit number"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Category</label>
                      <input
                        type="text"
                        value={formData.category}
                        onChange={e => setFormData({ ...formData, category: e.target.value })}
                        className="form-input"
                        placeholder="e.g. Science"
                      />
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Publisher</label>
                    <input
                      type="text"
                      value={formData.publisher}
                      onChange={e => setFormData({ ...formData, publisher: e.target.value })}
                      className="form-input"
                      placeholder="Publisher name"
                    />
                  </div>
                  <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">Year</label>
                      <input
                        type="number"
                        value={formData.year_published}
                        onChange={e => setFormData({ ...formData, year_published: parseInt(e.target.value) })}
                        className="form-input"
                        placeholder="YYYY"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Total Copies</label>
                      <input
                        type="number"
                        min={1}
                        value={formData.total_copies}
                        onChange={e => setFormData({ ...formData, total_copies: parseInt(e.target.value) })}
                        className="form-input"
                      />
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Shelf Location</label>
                    <input
                      type="text"
                      value={formData.shelf_location}
                      onChange={e => setFormData({ ...formData, shelf_location: e.target.value })}
                      className="form-input"
                      placeholder="e.g. A-12-3"
                    />
                  </div>
                </div>
              </div>

              <div className="mt-8 pt-6 border-t border-border flex gap-4">
                <button
                  type="button"
                  onClick={() => setShowAddModal(false)}
                  className="flex-1 py-4 border border-border text-text-secondary hover:bg-background-alt rounded-2xl transition-all font-black uppercase tracking-widest text-xs"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  form="books-add-form"
                  className="flex-1 py-4 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl shadow-primary/10 active:scale-95"
                >
                  {editingBook ? 'Update Book Record' : 'Commit to Catalog'}
                </button>              </div>
            </form>
          </ModalBody>
        </Modal>
      )}


      {/* Bulk Upload Modal */}
      {showBulkModal && (
        <Modal
          open={true}
          onClose={() => { setShowBulkModal(false); setBulkStatus(null); }}
          title="Bulk Import"
          icon={UploadCloud}
          maxWidth="max-w-4xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0 dark:bg-background/50">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <UploadCloud size={180} />
              </div>
              <div className="relative z-10">
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Upload CSV catalog list</p>
              </div>
            </div>

            <div className="overflow-y-auto p-10 space-y-8 custom-scrollbar">
              <div className="bg-primary/5 dark:bg-primary/10 border border-primary/10 rounded-2xl p-6">
                <h3 className="text-xs font-black uppercase text-primary tracking-widest mb-2 flex items-center gap-2">
                  <FileText size={16} />
                  CSV Column Guide
                </h3>
                <p className="text-[0.65rem] font-bold text-text-muted mb-4">Paste your comma-separated values (CSV) below. Ensure the first line contains headers.</p>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
                  {[
                    { col: 'title', req: true, desc: 'Full book title' },
                    { col: 'author', req: false, desc: 'Author name' },
                    { col: 'isbn', req: false, desc: '13-digit ISBN' },
                    { col: 'category', req: false, desc: 'Genre/Subject' },
                    { col: 'publisher', req: false, desc: 'Publisher name' },
                    { col: 'year_published', req: false, desc: 'YYYY format' },
                    { col: 'total_copies', req: false, desc: 'Default: 1' },
                    { col: 'shelf_location', req: false, desc: 'e.g. A-1' },
                  ].map((guide, i) => (
                    <div key={i} className="bg-card p-3 rounded-xl border border-border shadow-sm">
                      <p className="text-[0.7rem] font-black uppercase text-primary tracking-widest">
                        {guide.col} {guide.req && <span className="text-red-500">*</span>}
                      </p>
                      <p className="text-[0.65rem] text-text-muted mt-1 font-medium leading-relaxed">{guide.desc}</p>
                    </div>
                  ))}
                </div>
              </div>

              <form onSubmit={handleBulkUpload} className="space-y-6">
                <div className="space-y-2">
                  <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">CSV Data Input</label>
                  <textarea
                    rows={8}
                    value={bulkData}
                    onChange={e => setBulkData(e.target.value)}
                    className="w-full px-4 py-3 bg-background border border-border rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all font-mono text-xs text-text placeholder:text-text-muted/40"
                    placeholder={"title,author,isbn,category\nModern Physics,John Doe,1234567890,Science\nAdvanced Arts,Jane Smith,,Fine Arts"}
                  />
                </div>

                {bulkStatus && (
                  <div className={`p-6 rounded-2xl border ${bulkStatus.failed === 0 ? 'bg-emerald-500/5 border-emerald-500/20 text-emerald-600' : 'bg-amber-500/5 border-amber-500/20 text-amber-600'}`}>
                    <div className="flex items-center justify-between mb-3">
                      <p className="text-xs font-black uppercase tracking-widest">Import Statistics</p>
                      <div className="flex gap-4">
                        <span className="text-xs font-black text-emerald-600 bg-emerald-500/10 border border-emerald-500/20 px-2.5 py-0.5 rounded-full">Success: {bulkStatus.success}</span>
                        <span className="text-xs font-black text-rose-600 bg-rose-500/10 border border-rose-500/20 px-2.5 py-0.5 rounded-full">Failed: {bulkStatus.failed}</span>
                      </div>
                    </div>
                    {bulkStatus.errors.length > 0 && (
                      <ul className="text-[0.65rem] text-rose-600 space-y-1.5 max-h-36 overflow-y-auto mt-3 p-3 bg-rose-500/5 rounded-xl border border-rose-500/10 font-semibold">
                        {bulkStatus.errors.map((err, i) => (
                          <li key={i}>• <strong>{err.title}:</strong> {err.error}</li>
                        ))}
                      </ul>
                    )}
                  </div>
                )}

                <div className="pt-6 border-t border-border flex gap-4">
                  <button
                    type="button"
                    onClick={() => {
                      setShowBulkModal(false);
                      setBulkStatus(null);
                    }}
                    className="flex-1 py-4 border border-border text-text-secondary hover:bg-background-alt rounded-2xl transition-all font-black uppercase tracking-widest text-xs"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={!bulkData.trim()}
                    className="flex-1 py-4 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl shadow-primary/10 active:scale-95 disabled:opacity-50 disabled:grayscale"
                  >
                    Process Catalog Upload
                  </button>
                </div>
              </form>
            </div>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}
