import { useEffect, useState } from 'react';
import api from '../../store/auth';
import { 
  Book, BookOpen, Library as LibraryIcon, 
  Search, Plus, Filter, Download, 
  ChevronRight, Bookmark, Clock, CheckCircle2,
  Trash2, Edit2, BookmarkPlus, ArrowRight,
  Info, Sparkles, MapPin, Hash, Printer, MoreHorizontal,
  X
} from 'lucide-react';

export default function Library() {
  const [books, setBooks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingBook, setEditingBook] = useState<any>(null);
  const [issues, setIssues] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState('books');
  const [form, setForm] = useState({
    isbn: '',
    title: '',
    author: '',
    category: '',
    publisher: '',
    year_published: '',
    total_copies: 1,
    shelf_location: '',
  });

  useEffect(() => {
    loadBooks();
    loadIssues();
  }, []);

  const loadBooks = async () => {
    try {
      const res = await api.get('/library/books');
      setBooks(res.data || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const loadIssues = async () => {
    try {
      const res = await api.get('/library/issues');
      setIssues(res.data || []);
    } catch (err) {
      console.error(err);
    }
  };

  const saveBook = async () => {
    try {
      if (editingBook) {
        await api.put(`/library/books/${editingBook.id}`, {
          ...form,
          year_published: Number(form.year_published),
          total_copies: Number(form.total_copies),
        });
      } else {
        await api.post('/library/books', {
          ...form,
          year_published: Number(form.year_published),
          total_copies: Number(form.total_copies),
        });
      }
      setShowModal(false);
      setEditingBook(null);
      setForm({
        isbn: '',
        title: '',
        author: '',
        category: '',
        publisher: '',
        year_published: '',
        total_copies: 1,
        shelf_location: '',
      });
      loadBooks();
    } catch (err) {
      console.error(err);
      alert('Failed to save book intelligence record');
    }
  };

  const filtered = books.filter((book) =>
    (book.title || '').toLowerCase().includes(search.toLowerCase()) ||
    (book.author || '').toLowerCase().includes(search.toLowerCase())
  );

  const stats = [
    { label: 'System Inventory', value: books.length, icon: Book, color: 'blue', trend: 'Records' },
    { label: 'Available Assets', value: books.filter(b => b.available_copies > 0).length, icon: CheckCircle2, color: 'emerald', trend: 'Live' },
    { label: 'Active Circulations', value: issues.filter(i => i.status === 'issued').length, icon: Clock, color: 'orange', trend: 'Out' },
    { label: 'Subject Divisions', value: new Set(books.map(b => b.category)).size, icon: Bookmark, color: 'purple', trend: 'Genres' },
  ];

  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 'orange': return 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-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';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium 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 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 Bento Grid */}
      <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">
        {/* Navigation Tabs */}
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-grow lg:flex-grow-0 min-w-0">
          {[
            { id: 'books', label: 'Asset Catalog', icon: LibraryIcon },
            { id: 'issues', label: 'Circulation Log', icon: Clock },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                flex-1 px-8 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}
              {tab.id === 'issues' && <span className="ml-1 opacity-50">({issues.filter(i => i.status === 'issued').length})</span>}
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <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={activeTab === 'books' ? "Search system catalog by title, author or ISBN..." : "Search active circulations..."}
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>

        <button className="px-5 py-3 bg-muted/50 hover:bg-muted text-text-muted rounded-2xl border border-border transition-all flex items-center justify-center gap-2">
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest text-text-muted">Advanced Query</span>
        </button>
      </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">
          {filtered.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>
          ) : (
            filtered.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 Intelligence</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 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 || '',
                                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-xs transition-all border border-border flex items-center justify-center gap-2"
                    >
                        <Edit2 size={14} />
                        Update
                    </button>
                    <button 
                        onClick={async () => {
                            const dueDate = prompt('Enter Return Protocol Timestamp (YYYY-MM-DD)');
                            if (!dueDate) return;
                            try {
                                await api.post('/library/issues', { book_id: book.id, user_id: 1, due_date: dueDate });
                                loadBooks(); loadIssues();
                                alert('Asset circulation initiated successfully');
                            } catch (err) { alert('Protocol failure: asset reserved'); }
                        }}
                        className="flex-[2] py-3 bg-primary text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 flex items-center justify-center gap-2"
                    >
                        <BookmarkPlus size={16} />
                        Initiate Issue
                    </button>
                    <button 
                        onClick={async () => {
                            if (!window.confirm(`Delete record for "${book.title}"?`)) return;
                            try {
                                await api.delete(`/library/books/${book.id}`);
                                loadBooks();
                            } catch (err) { alert('Deletion failed'); }
                        }}
                        className="p-3 bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 rounded-xl hover:bg-rose-100 dark:hover:bg-rose-900/40 transition-all border border-rose-100 dark:border-rose-800"
                    >
                        <Trash2 size={16} />
                    </button>
                </div>
              </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">Circulated Resource</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">Circulation Control</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                        {issues.filter(i => i.status === 'issued').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 asset circulations detected</p>
                                </td>
                            </tr>
                        ) : (
                            issues.filter(i => i.status === 'issued').map((issue) => (
                                <tr key={issue.id} className="hover:bg-muted/30 transition-colors group">
                                    <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 shadow-inner">
                                                <Book size={18} />
                                            </div>
                                            <div>
                                                <p className="text-[0.95rem] font-bold text-text">{issue.book_title}</p>
                                                <p className="text-[0.6rem] text-text-muted font-black tracking-tighter uppercase mt-0.5">UID: REG-{issue.id.toString().padStart(4, '0')}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5">
                                        <span className="px-3 py-1 bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400 text-[0.6rem] font-black rounded-lg uppercase tracking-widest border border-orange-200 dark:border-orange-800">
                                            {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-[0.75rem]">
                                            <Clock size={14} className="opacity-50" />
                                            {issue.due_date}
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        <button 
                                            onClick={async () => {
                                                try {
                                                    await api.put(`/library/issues/${issue.id}/return`);
                                                    loadBooks(); loadIssues();
                                                    alert('Asset returned to system successfully');
                                                } catch (err) { alert('Return failed'); }
                                            }}
                                            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 flex items-center gap-2 ml-auto"
                                        >
                                            <CheckCircle2 size={14} />
                                            Record Return
                                        </button>
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
      )}

      {/* Modal Infrastructure */}
      {showModal && (
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[2.5rem] w-full max-w-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border flex flex-col max-h-[90vh]">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">
                    {editingBook ? 'Update Asset Intelligence' : 'Register New Resource'}
                </h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                    {editingBook ? `Syncing Record: ${editingBook.isbn}` : 'Add a new asset to the system catalog'}
                </p>
              </div>
              <button onClick={() => setShowModal(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>

            <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 Protocol</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>
          </div>
        </div>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); }
      `}</style>
    </div>
  );
}
