import { useState, useEffect, useRef } from 'react';
import { 
  Package, Search, Plus, Filter, ArrowUpRight, ArrowDownRight, 
  History, UserPlus, RefreshCcw, LayoutGrid, List, AlertTriangle,
  PackageCheck, PackagePlus, ArrowLeftRight, ChevronRight, MoreVertical, CheckCircle2,
  Building, Home, ChefHat, MapPin, ClipboardList, BookOpen, User, Briefcase, Calendar, DollarSign
} from 'lucide-react';
import { useInventoryStore } from '../../store/inventory';
import { Modal, ModalBody } from '../../components/ui/Modal';
import api from '../../store/auth';

export default function Inventory() {
  const { 
    items, categories, locations, suppliers, stock, issues, loading,
    fetchItems, fetchCategories, fetchLocations, fetchSuppliers, fetchStock, fetchIssues,
    recordTransaction, issueItem, returnItem, createItem, createCategory, createSupplier
  } = useInventoryStore();

  const [activeTab, setActiveTab] = useState<'items' | 'stock' | 'issues' | 'assets'>('items');
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [showAddModal, setShowAddModal] = useState(false);
  const [showTransactionModal, setShowTransactionModal] = useState(false);
  const [showIssueModal, setShowIssueModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);

  // School Assets views state
  const [selectedAssetCategory, setSelectedAssetCategory] = useState<'class' | 'hostel' | 'ground' | 'kitchen' | 'department' | 'staff' | 'student'>('class');
  const [expandedEntityId, setExpandedEntityId] = useState<string | number | null>(null);

  // Custom options state for modals
  const [showCustomCategoryInput, setShowCustomCategoryInput] = useState(false);
  const [showCustomSupplierInput, setShowCustomSupplierInput] = useState(false);
  const [selectedCategoryVal, setSelectedCategoryVal] = useState('');
  const [selectedSupplierVal, setSelectedSupplierVal] = useState('');

  // Auxiliary data states
  const [classesList, setClassesList] = useState<any[]>([]);
  const [hostelsList, setHostelsList] = useState<any[]>([]);
  const [departmentsList, setDepartmentsList] = useState<any[]>([]);
  const [usersList, setUsersList] = useState<any[]>([]);
  const [clubsList, setClubsList] = useState<any[]>([]);

  // Issue modal selectors
  const [issueToType, setIssueToType] = useState<string>('staff');
  const [selectedIssuedToId, setSelectedIssuedToId] = useState<string | number>('');
  const [userSearchQuery, setUserSearchQuery] = useState('');
  const [showUserDropdown, setShowUserDropdown] = useState(false);
  const [itemSearchQuery, setItemSearchQuery] = useState('');
  const [showItemDropdown, setShowItemDropdown] = useState(false);
  const [targetSearchQuery, setTargetSearchQuery] = useState('');
  const [showTargetDropdown, setShowTargetDropdown] = useState(false);

  const closeIssueModal = () => {
    setShowIssueModal(false);
    setItemSearchQuery('');
    setShowItemDropdown(false);
    setTargetSearchQuery('');
    setShowTargetDropdown(false);
    setUserSearchQuery('');
    setShowUserDropdown(false);
  };

  // Return modal states
  const [showReturnModal, setShowReturnModal] = useState(false);
  const [selectedIssueForReturn, setSelectedIssueForReturn] = useState<any | null>(null);
  const [returnQuantity, setReturnQuantity] = useState<number>(0);
  const [returnLocation, setReturnLocation] = useState<string | number>('');
  const [returnCondition, setReturnCondition] = useState<string>('Good');

  const groundsList = [
    { id: 101, name: 'Main Sports Field' },
    { id: 102, name: 'Athletics Track' },
    { id: 103, name: 'Tennis & Basketball Courts' },
    { id: 104, name: 'Swimming Pool Facility' },
    { id: 105, name: 'General Campus Gardens' },
    { id: 106, name: 'School Main Square' }
  ];

  const kitchensList = hostelsList.map(h => ({
    id: h.id,
    name: `${h.name} Kitchen`
  }));

  useEffect(() => {
    fetchItems();
    fetchCategories();
    fetchLocations();
    fetchSuppliers();
    fetchStock();
    fetchIssues();
    loadAuxiliaryData();
  }, []);

  const loadAuxiliaryData = async () => {
    try {
      const [resClasses, resHostels, resDeps, resUsers, resClubs] = await Promise.all([
        api.get('/classes').catch(() => ({ data: [] })),
        api.get('/hostels').catch(() => ({ data: [] })),
        api.get('/departments').catch(() => ({ data: [] })),
        api.get('/users', { params: { limit: 1000 } }).catch(() => ({ data: { users: [] } })),
        api.get('/clubs').catch(() => ({ data: [] }))
      ]);

      setClassesList(resClasses.data || []);
      setHostelsList(resHostels.data || []);
      setDepartmentsList(resDeps.data || []);
      const usersData = resUsers.data?.users || resUsers.data || [];
      setUsersList(Array.isArray(usersData) ? usersData : []);
      setClubsList(resClubs.data || []);
    } catch (e) {
      console.error('Failed to load auxiliary inventory data', e);
    }
  };

  const getIssuedToName = (issue: any) => {
    switch (issue.issued_to_type) {
      case 'class':
        return classesList.find(c => c.id === issue.issued_to_id)?.name || `Class (ID: ${issue.issued_to_id})`;
      case 'hostel':
        return hostelsList.find(h => h.id === issue.issued_to_id)?.name || `Hostel (ID: ${issue.issued_to_id})`;
      case 'department':
        return departmentsList.find(d => d.id === issue.issued_to_id)?.name || `Department (ID: ${issue.issued_to_id})`;
      case 'ground':
        return groundsList.find(g => g.id === issue.issued_to_id)?.name || `Grounds (ID: ${issue.issued_to_id})`;
      case 'kitchen':
        const hName = hostelsList.find(h => h.id === issue.issued_to_id)?.name;
        return hName ? `${hName} Kitchen` : `Kitchen (ID: ${issue.issued_to_id})`;
      case 'club':
      case 'sport':
        return clubsList.find(c => c.id === issue.issued_to_id)?.name || `Club/Sport (ID: ${issue.issued_to_id})`;
      case 'student':
      case 'staff':
      default:
        const usr = usersList.find(u => u.id === issue.issued_to_id);
        return usr ? `${usr.first_name} ${usr.last_name} (${usr.role.toUpperCase()})` : `${issue.issued_to_type} (ID: ${issue.issued_to_id})`;
    }
  };

  const handleReturnItemSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedIssueForReturn) return;
    try {
      await returnItem(selectedIssueForReturn.id, {
        quantity: Number(returnQuantity),
        condition: returnCondition,
        store_id: Number(returnLocation)
      });
      setShowReturnModal(false);
      alert('Items returned and catalog stock levels synced successfully.');
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to process return');
    }
  };

  const filteredItems = items.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(search.toLowerCase()) || 
                         item.code?.toLowerCase().includes(search.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || item.category_id === parseInt(selectedCategory);
    return matchesSearch && matchesCategory;
  });

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight flex items-center gap-3">
            <Package className="text-primary" size={32} />
            Inventory & Supplies
          </h1>
          <p className="text-text-muted font-medium mt-1">Manage school resources, track stock levels and item issues</p>
        </div>
        <div className="flex items-center gap-3 w-full md:w-auto">
          <button 
            onClick={() => setShowAddModal(true)}
            className="w-full md:w-auto flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-white rounded-xl font-bold hover:bg-primary-dark transition-all shadow-lg shadow-primary/20"
          >
            <Plus size={20} />
            Add Item
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div 
        className="flex items-center gap-1 bg-card p-1 rounded-2xl border border-border w-full md:w-fit overflow-x-auto whitespace-nowrap"
        style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
      >
        <button
          onClick={() => setActiveTab('items')}
          className={`flex-shrink-0 px-5 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2 ${activeTab === 'items' ? 'bg-primary text-white shadow-md' : 'text-text-muted hover:bg-background'}`}
        >
          <LayoutGrid size={18} />
          Catalog
        </button>
        <button
          onClick={() => setActiveTab('stock')}
          className={`flex-shrink-0 px-5 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2 ${activeTab === 'stock' ? 'bg-primary text-white shadow-md' : 'text-text-muted hover:bg-background'}`}
        >
          <PackageCheck size={18} />
          Current Stock
        </button>
        <button
          onClick={() => setActiveTab('issues')}
          className={`flex-shrink-0 px-5 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2 ${activeTab === 'issues' ? 'bg-primary text-white shadow-md' : 'text-text-muted hover:bg-background'}`}
        >
          <History size={18} />
          Issued Items
        </button>
        <button
          onClick={() => setActiveTab('assets')}
          className={`flex-shrink-0 px-5 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2 ${activeTab === 'assets' ? 'bg-primary text-white shadow-md' : 'text-text-muted hover:bg-background'}`}
        >
          <ClipboardList size={18} />
          School Assets
        </button>
      </div>

      {/* Main Content */}
      <div className="space-y-4">
        {/* Filters */}
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" size={20} />
            <input
              type="text"
              placeholder={activeTab === 'assets' ? "Search locations, staff or students..." : "Search items by name, code or barcode..."}
              className="w-full pl-12 pr-4 py-3 bg-card border border-border rounded-2xl focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all outline-none font-medium"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          {activeTab === 'items' && (
            <div className="flex items-center gap-3">
              <select
                className="px-4 py-3 bg-card border border-border rounded-2xl outline-none font-bold text-sm focus:ring-2 focus:ring-primary/20"
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
              >
                <option value="all">All Categories</option>
                {categories.map(cat => (
                  <option key={cat.id} value={cat.id}>{cat.name}</option>
                ))}
              </select>
              <button className="p-3 bg-card border border-border rounded-2xl text-text-muted hover:text-primary transition-colors">
                <Filter size={20} />
              </button>
            </div>
          )}
        </div>

        {activeTab === 'items' && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredItems.map(item => (
              <div key={item.id} className="bg-card border border-border rounded-[2rem] p-6 hover:shadow-xl transition-all group relative overflow-hidden">
                <div className="absolute top-0 right-0 p-4">
                   <button className="p-2 text-text-muted hover:text-primary transition-colors">
                     <MoreVertical size={20} />
                   </button>
                </div>
                
                <div className="flex items-start gap-4 mb-6">
                  <div className="w-16 h-16 bg-primary/5 rounded-2xl flex items-center justify-center text-primary group-hover:scale-110 transition-transform duration-500">
                    <Package size={32} />
                  </div>
                  <div>
                    <h4 className="font-black text-xl text-text tracking-tight group-hover:text-primary transition-colors">{item.name}</h4>
                    <div className="flex items-center gap-2 text-xs font-bold text-text-muted mt-1 uppercase tracking-widest">
                      <span>{item.code || 'NO CODE'}</span>
                      <span>•</span>
                      <span>{item.category_name || 'Uncategorized'}</span>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4 mb-6">
                  <div className="p-3 bg-background rounded-2xl border border-border">
                    <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-wider mb-1">Stock Level</p>
                    <div className="flex items-center justify-between">
                      <span className={`text-lg font-black ${item.total_stock && item.total_stock <= item.reorder_level ? 'text-rose-500' : 'text-emerald-500'}`}>
                        {item.total_stock || 0}
                      </span>
                      <span className="text-[0.6rem] font-bold text-text-muted uppercase">{item.unit}</span>
                    </div>
                  </div>
                  <div className="p-3 bg-background rounded-2xl border border-border">
                    <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-wider mb-1">Unit Price</p>
                    <div className="flex items-center justify-between">
                      <span className="text-lg font-black text-text">${item.purchase_price}</span>
                      <span className="text-[0.6rem] font-bold text-text-muted uppercase">USD</span>
                    </div>
                  </div>
                </div>

                <div className="flex gap-2">
                  <button 
                    onClick={() => {
                      setSelectedItem(item);
                      setShowTransactionModal(true);
                    }}
                    className="flex-1 py-3 bg-emerald-500/10 text-emerald-600 rounded-xl font-bold text-xs uppercase tracking-widest hover:bg-emerald-500 hover:text-white transition-all flex items-center justify-center gap-2"
                  >
                    <PackagePlus size={16} />
                    Stock In
                  </button>
                  <button 
                    onClick={() => {
                      setSelectedItem(item);
                      setItemSearchQuery(item.name);
                      setSelectedIssuedToId('');
                      setUserSearchQuery('');
                      setTargetSearchQuery('');
                      setShowIssueModal(true);
                    }}
                    className="flex-1 py-3 bg-primary/10 text-primary rounded-xl font-bold text-xs uppercase tracking-widest hover:bg-primary hover:text-white transition-all flex items-center justify-center gap-2"
                  >
                    <UserPlus size={16} />
                    Issue
                  </button>
                </div>

                {item.total_stock && item.total_stock <= item.reorder_level && (
                  <div className="mt-4 flex items-center gap-2 p-2.5 bg-rose-50 border border-rose-100 rounded-xl text-rose-600 animate-pulse">
                    <AlertTriangle size={14} />
                    <span className="text-[0.65rem] font-black uppercase tracking-wider">Low Stock Warning</span>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {activeTab === 'stock' && (
          <div className="space-y-4">
            {/* Mobile Card View */}
            <div className="grid grid-cols-1 gap-4 md:hidden">
              {stock.map(s => (
                <div key={s.id} className="bg-card border border-border rounded-3xl p-5 hover:shadow-md transition-all flex flex-col gap-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-primary/5 rounded-xl flex items-center justify-center text-primary">
                        <Package size={20} />
                      </div>
                      <div>
                        <p className="font-bold text-text text-sm">{s.item_name}</p>
                        <p className="text-[0.6rem] text-text-muted font-bold uppercase tracking-wider">SKU: {s.id.toString().padStart(5, '0')}</p>
                      </div>
                    </div>
                    <span className={`px-2.5 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-wider ${s.quantity > 0 ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : 'bg-rose-50 text-rose-600 border border-rose-100'}`}>
                      {s.quantity > 0 ? 'In Stock' : 'Out'}
                    </span>
                  </div>

                  <div className="flex items-center justify-between bg-background p-3 rounded-2xl border border-border">
                    <div>
                      <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-wider">Storage Location</p>
                      <p className="text-xs font-bold text-text mt-0.5">{s.store_name}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-wider">In Stock</p>
                      <p className="text-sm font-black text-text mt-0.5">
                        {s.quantity} <span className="text-[0.65rem] font-bold text-text-muted uppercase">{s.unit}</span>
                      </p>
                    </div>
                  </div>

                  <div className="flex justify-end border-t border-border/60 pt-3">
                    <button className="flex items-center gap-2 px-4 py-2 bg-muted/65 hover:bg-muted text-text-muted hover:text-primary rounded-xl font-bold text-xs uppercase tracking-wider transition-all">
                      <ArrowLeftRight size={14} />
                      Transfer Stock
                    </button>
                  </div>
                </div>
              ))}
            </div>

            {/* Desktop Table View */}
            <div className="hidden md:block bg-card border border-border rounded-[2rem] overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full border-collapse">
                  <thead>
                    <tr className="bg-background border-b border-border">
                      <th className="px-6 py-4 text-left text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Item</th>
                      <th className="px-6 py-4 text-left text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Location</th>
                      <th className="px-6 py-4 text-center text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Quantity</th>
                      <th className="px-6 py-4 text-center text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Status</th>
                      <th className="px-6 py-4 text-right text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {stock.map(s => (
                      <tr key={s.id} className="hover:bg-background/50 transition-colors group">
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-3">
                            <div className="w-10 h-10 bg-primary/5 rounded-xl flex items-center justify-center text-primary group-hover:scale-110 transition-transform">
                              <Package size={20} />
                            </div>
                            <div>
                              <p className="font-bold text-text">{s.item_name}</p>
                              <p className="text-[0.65rem] text-text-muted font-bold uppercase tracking-wider">SKU: {s.id.toString().padStart(5, '0')}</p>
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <span className="px-3 py-1 bg-slate-100 text-slate-600 rounded-full text-[0.65rem] font-black uppercase tracking-wider">{s.store_name}</span>
                        </td>
                        <td className="px-6 py-4 text-center">
                          <span className="font-black text-text text-lg">{s.quantity}</span>
                          <span className="text-[0.65rem] text-text-muted ml-1 uppercase font-bold">{s.unit}</span>
                        </td>
                        <td className="px-6 py-4 text-center">
                          <span className={`px-3 py-1 rounded-full text-[0.65rem] font-black uppercase tracking-wider ${s.quantity > 0 ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : 'bg-rose-50 text-rose-600 border border-rose-100'}`}>
                            {s.quantity > 0 ? 'In Stock' : 'Out of Stock'}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-right">
                          <button className="p-2 text-text-muted hover:text-primary transition-colors">
                            <ArrowLeftRight size={18} />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'issues' && (
          <div className="space-y-4">
            {issues.map(issue => (
              <div key={issue.id} className="bg-card border border-border rounded-3xl p-5 md:p-6 flex flex-col md:flex-row md:items-center justify-between gap-5 hover:shadow-lg transition-all border-l-4 border-l-primary">
                <div className="flex items-center gap-4">
                   <div className="w-12 h-12 bg-primary/5 rounded-2xl flex items-center justify-center text-primary shrink-0">
                      <UserPlus size={24} />
                   </div>
                   <div className="min-w-0">
                      <h4 className="font-black text-text text-base md:text-lg tracking-tight truncate">{issue.item_name}</h4>
                      <p className="text-[0.7rem] font-bold text-text-muted uppercase tracking-wider truncate mt-0.5">Issued to: {getIssuedToName(issue)}</p>
                   </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-8 bg-background/50 md:bg-transparent p-4 md:p-0 rounded-2xl border border-border md:border-none">
                   <div>
                      <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mb-1">Quantity</p>
                      <p className="font-black text-text text-sm md:text-base">{issue.returned_quantity > 0 ? `${issue.quantity - issue.returned_quantity} left / ` : ''}{issue.quantity}</p>
                   </div>
                   <div>
                      <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mb-1">Issue Date</p>
                      <p className="font-bold text-text text-xs md:text-sm">{new Date(issue.issue_date).toLocaleDateString()}</p>
                   </div>
                   <div>
                      <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mb-1">Status</p>
                      <span className={`inline-block px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                        issue.status === 'returned' ? 'bg-emerald-50 text-emerald-600 border-emerald-200' : 
                        issue.status === 'issued' ? 'bg-amber-50 text-amber-600 border-amber-200' : 
                        'bg-rose-50 text-rose-600 border-rose-200'
                      }`}>
                        {issue.status}
                      </span>
                   </div>
                   <div>
                      <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mb-1">Issued By</p>
                      <p className="font-bold text-text text-xs">{issue.issuer_name}</p>
                   </div>
                </div>

                <div className="flex items-center gap-2 w-full md:w-auto">
                   {issue.status !== 'returned' && (
                     <button 
                        onClick={() => {
                          setSelectedIssueForReturn(issue);
                          setReturnQuantity(issue.quantity - issue.returned_quantity);
                          setReturnLocation(locations[0]?.id || 1);
                          setReturnCondition('Good');
                          setShowReturnModal(true);
                        }}
                        className="flex-1 md:flex-initial px-4 py-2.5 bg-emerald-500 hover:bg-emerald-600 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all text-center"
                     >
                       Return
                     </button>
                   )}
                   <button className="p-2.5 bg-background border border-border rounded-xl text-text-muted hover:text-primary transition-colors">
                      <ChevronRight size={20} />
                   </button>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* School Assets tab content */}
        {activeTab === 'assets' && (
          <div className="space-y-6 animate-in fade-in duration-300">
            {/* Category Selection Pills */}
            <div 
              className="flex items-center gap-2 mb-4 bg-card/60 p-1.5 rounded-2xl border border-border overflow-x-auto whitespace-nowrap"
              style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
            >
              {[
                { id: 'class', label: 'Classes', count: classesList.length },
                { id: 'hostel', label: 'Hostels', count: hostelsList.length },
                { id: 'kitchen', label: 'Kitchens', count: kitchensList.length },
                { id: 'ground', label: 'Grounds', count: groundsList.length },
                { id: 'department', label: 'Departments', count: departmentsList.length },
                { id: 'staff', label: 'Staff / Teachers', count: usersList.filter(u => u.role !== 'student').length },
                { id: 'student', label: 'Students', count: usersList.filter(u => u.role === 'student').length },
              ].map(cat => (
                <button
                  key={cat.id}
                  onClick={() => {
                    setSelectedAssetCategory(cat.id as any);
                    setExpandedEntityId(null);
                  }}
                  className={`flex-shrink-0 px-4 py-2.5 rounded-xl text-xs font-black uppercase tracking-wider transition-all flex items-center gap-2 ${
                    selectedAssetCategory === cat.id 
                      ? 'bg-primary text-white shadow-md' 
                      : 'text-text-muted hover:bg-background hover:text-text'
                  }`}
                >
                  {cat.label}
                  <span className={`px-2 py-0.5 rounded-full text-[0.65rem] ${
                    selectedAssetCategory === cat.id ? 'bg-white/20 text-white' : 'bg-background border border-border text-text-muted'
                  }`}>
                    {cat.count}
                  </span>
                </button>
              ))}
            </div>

            {/* Entities Grid */}
            {(() => {
              const searchLower = search.toLowerCase();
              const filteredEntities = (() => {
                switch (selectedAssetCategory) {
                  case 'class':
                    return classesList.filter(c => c.name.toLowerCase().includes(searchLower));
                  case 'hostel':
                    return hostelsList.filter(h => h.name.toLowerCase().includes(searchLower));
                  case 'ground':
                    return groundsList.filter(g => g.name.toLowerCase().includes(searchLower));
                  case 'kitchen':
                    return kitchensList.filter(k => k.name.toLowerCase().includes(searchLower));
                  case 'department':
                    return departmentsList.filter(d => d.name.toLowerCase().includes(searchLower));
                  case 'staff':
                    return usersList.filter(u => u.role !== 'student' && `${u.first_name} ${u.last_name}`.toLowerCase().includes(searchLower));
                  case 'student':
                    return usersList.filter(u => u.role === 'student' && `${u.first_name} ${u.last_name}`.toLowerCase().includes(searchLower));
                  default:
                    return [];
                }
              })();

              if (filteredEntities.length === 0) {
                return (
                  <div className="text-center py-12 bg-card border border-border rounded-3xl">
                    <Package className="mx-auto text-text-muted mb-3" size={48} />
                    <p className="font-bold text-text">No locations or borrowers found</p>
                    <p className="text-sm text-text-muted mt-1">Try adjusting your search query</p>
                  </div>
                );
              }

              return (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {filteredEntities.map(entity => {
                    const name = selectedAssetCategory === 'staff' || selectedAssetCategory === 'student'
                      ? `${entity.first_name} ${entity.last_name}`
                      : entity.name;

                    const subtitle = (() => {
                      switch (selectedAssetCategory) {
                        case 'class': return 'Classroom Assets';
                        case 'hostel': return 'Hostel Block Equipment';
                        case 'kitchen': return 'Kitchen & Cooking Assets';
                        case 'ground': return 'Sports & Ground Facilities';
                        case 'department': return 'Departmental Inventory';
                        case 'staff': return `Teacher Account (${entity.role.toUpperCase()})`;
                        case 'student': return 'Student Equipment Pool';
                        default: return 'School Location';
                      }
                    })();

                    const Icon = (() => {
                      switch (selectedAssetCategory) {
                        case 'class': return BookOpen;
                        case 'hostel': return Home;
                        case 'kitchen': return ChefHat;
                        case 'ground': return MapPin;
                        case 'department': return Briefcase;
                        case 'staff': return User;
                        case 'student': return User;
                        default: return ClipboardList;
                      }
                    })();

                    const iconColorClass = (() => {
                      switch (selectedAssetCategory) {
                        case 'class': return 'text-primary bg-primary/5';
                        case 'hostel': return 'text-indigo-500 bg-indigo-500/5';
                        case 'kitchen': return 'text-amber-500 bg-amber-500/5';
                        case 'ground': return 'text-emerald-500 bg-emerald-500/5';
                        case 'department': return 'text-violet-500 bg-violet-500/5';
                        case 'staff': return 'text-teal-500 bg-teal-500/5';
                        case 'student': return 'text-blue-500 bg-blue-500/5';
                        default: return 'text-primary bg-primary/5';
                      }
                    })();

                    const entityIssues = issues.filter(issue => 
                      issue.issued_to_type === selectedAssetCategory && 
                      Number(issue.issued_to_id) === Number(entity.id) &&
                      issue.status !== 'returned'
                    );

                    const distinctItems = entityIssues.length;
                    const totalUnits = entityIssues.reduce((sum, iss) => sum + (iss.quantity - iss.returned_quantity), 0);
                    const isExpanded = expandedEntityId === entity.id;

                    return (
                      <div key={entity.id} className="bg-card border border-border rounded-[2rem] p-6 hover:shadow-xl transition-all group flex flex-col justify-between">
                        <div>
                          {/* Card Header */}
                          <div className="flex items-start gap-4 mb-5">
                            <div className={`w-14 h-14 rounded-2xl flex items-center justify-center group-hover:scale-110 transition-transform duration-500 ${iconColorClass}`}>
                              <Icon size={28} />
                            </div>
                            <div>
                              <h4 className="font-black text-lg text-text tracking-tight group-hover:text-primary transition-colors">{name}</h4>
                              <p className="text-[0.65rem] font-bold text-text-muted uppercase tracking-widest mt-0.5">{subtitle}</p>
                            </div>
                          </div>

                          {/* Stats Grid */}
                          <div className="grid grid-cols-2 gap-3 mb-5">
                            <div className="p-3.5 bg-background rounded-2xl border border-border">
                              <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-wider mb-1">Asset Types</p>
                              <p className="text-base font-black text-text">{distinctItems}</p>
                            </div>
                            <div className="p-3.5 bg-background rounded-2xl border border-border">
                              <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-wider mb-1">Active Qty</p>
                              <p className="text-base font-black text-text">{totalUnits}</p>
                            </div>
                          </div>
                        </div>

                        {/* Action Buttons */}
                        <div className="space-y-2">
                          <div className="flex gap-2">
                            <button
                              onClick={() => {
                                setExpandedEntityId(isExpanded ? null : entity.id);
                              }}
                              className="flex-1 py-2.5 bg-muted/60 text-text rounded-xl font-bold text-xs uppercase tracking-wider hover:bg-muted transition-all flex items-center justify-center gap-1.5"
                            >
                              <List size={14} />
                              {isExpanded ? 'Hide Assets' : `View (${distinctItems})`}
                            </button>
                            <button
                              onClick={() => {
                                setSelectedItem(null);
                                setItemSearchQuery('');
                                setIssueToType(selectedAssetCategory);
                                setSelectedIssuedToId(entity.id);
                                if (selectedAssetCategory === 'staff' || selectedAssetCategory === 'student') {
                                  setUserSearchQuery(`${name}`);
                                  setTargetSearchQuery('');
                                } else {
                                  setTargetSearchQuery(`${name}`);
                                  setUserSearchQuery('');
                                }
                                setShowIssueModal(true);
                              }}
                              className="px-3.5 py-2.5 bg-primary/10 text-primary rounded-xl font-bold text-xs hover:bg-primary hover:text-white transition-all flex items-center justify-center"
                              title="Allocate new asset"
                            >
                              <Plus size={16} />
                            </button>
                          </div>

                          {/* Expanded Detail Panel */}
                          {isExpanded && (
                            <div className="pt-3 border-t border-border mt-3 space-y-3 animate-in slide-in-from-top-2 duration-300">
                              <div className="flex items-center justify-between">
                                <span className="text-[0.6rem] font-black text-text-muted uppercase tracking-wider">Allocated Assets</span>
                              </div>

                              {entityIssues.length === 0 ? (
                                <p className="text-xs text-text-muted text-center py-4 bg-background/50 rounded-xl border border-border/50 border-dashed">No active assets allocated to this location.</p>
                              ) : (
                                <div className="space-y-2.5 max-h-60 overflow-y-auto custom-scrollbar pr-1">
                                  {entityIssues.map(iss => (
                                    <div key={iss.id} className="p-3 bg-background border border-border rounded-2xl flex items-center justify-between gap-3">
                                      <div className="flex-1 min-w-0">
                                        <p className="text-xs font-black text-text truncate">{iss.item_name}</p>
                                        <div className="flex flex-wrap items-center gap-x-2 text-[0.6rem] font-bold text-text-muted uppercase tracking-wider mt-0.5">
                                          <span>Qty: {iss.quantity - iss.returned_quantity}</span>
                                          {iss.returned_quantity > 0 && <span>({iss.returned_quantity} ret)</span>}
                                          <span>•</span>
                                          <span className="truncate">{new Date(iss.issue_date).toLocaleDateString()}</span>
                                        </div>
                                        {iss.purpose && (
                                          <p className="text-[0.6rem] text-text-muted mt-1 italic font-medium">"{iss.purpose}"</p>
                                        )}
                                      </div>
                                      <button
                                        onClick={() => {
                                          setSelectedIssueForReturn(iss);
                                          setReturnQuantity(iss.quantity - iss.returned_quantity);
                                          setReturnLocation(locations[0]?.id || 1);
                                          setReturnCondition('Good');
                                          setShowReturnModal(true);
                                        }}
                                        className="px-2.5 py-1.5 bg-emerald-500 hover:bg-emerald-600 text-white rounded-lg text-[0.55rem] font-black uppercase tracking-wider transition-all"
                                      >
                                        Return
                                      </button>
                                    </div>
                                  ))}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              );
            })()}
          </div>
        )}
      </div>

      {/* Transaction Modal (Add Stock) */}
      {showTransactionModal && (
        <Modal
          open={true}
          onClose={() => setShowTransactionModal(false)}
          title={`Add Stock: ${selectedItem?.name ?? ''}`}
          maxWidth="max-w-md"
          zIndex={100}
        >
          <ModalBody>
            <form id="inventory-add-stock-form" className="space-y-6" onSubmit={(e) => {
              e.preventDefault();
              const formData = new FormData(e.currentTarget);
              recordTransaction({
                item_id: selectedItem.id,
                store_id: parseInt(formData.get('store_id') as string),
                type: 'purchase',
                quantity: parseInt(formData.get('quantity') as string),
                unit_price: parseFloat(formData.get('unit_price') as string),
                reference_number: formData.get('reference') as string,
                notes: formData.get('notes') as string
              }).then(() => setShowTransactionModal(false));
            }}>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Quantity</label>
                  <div className="relative">
                    <input name="quantity" type="number" required className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold" />
                    <PackagePlus className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Unit Price ($)</label>
                  <div className="relative">
                    <input name="unit_price" type="number" step="0.01" required className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold" />
                    <DollarSign className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Storage Location</label>
                <div className="relative">
                  <select name="store_id" required className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold appearance-none">
                    {locations.map(l => (
                      <option key={l.id} value={l.id}>{l.name}</option>
                    ))}
                  </select>
                  <MapPin className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Reference #</label>
                <div className="relative">
                  <input name="reference" type="text" placeholder="PO-12345" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold" />
                  <ClipboardList className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Notes / Remarks</label>
                <div className="relative">
                  <input name="notes" type="text" placeholder="e.g. Regular replenishment" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold" />
                  <ClipboardList className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-4 bg-emerald-500 text-white rounded-2xl font-black uppercase tracking-[2px] text-xs shadow-lg shadow-emerald-500/20 hover:scale-[1.02] active:scale-95 transition-all"
              >
                {loading ? 'Processing...' : 'Complete Stock In'}
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Issue Modal */}
      {showIssueModal && (
        <Modal
          open={true}
          onClose={closeIssueModal}
          title={selectedItem ? `Issue: ${selectedItem.name}` : 'Issue School Asset'}
          maxWidth="max-w-md"
          zIndex={100}
        >
          <ModalBody>
            <form id="inventory-issue-form" className="space-y-5" onSubmit={(e) => {
              e.preventDefault();
              const formData = new FormData(e.currentTarget);
              if (!selectedIssuedToId) {
                alert('Please select a valid target borrower/entity.');
                return;
              }
              const itemId = selectedItem?.id || parseInt(formData.get('item_id') as string);
              if (!itemId) {
                alert('Please select a valid item to issue.');
                return;
              }
              issueItem({
                item_id: itemId,
                store_id: parseInt(formData.get('store_id') as string),
                issued_to_type: issueToType as any,
                issued_to_id: Number(selectedIssuedToId),
                quantity: parseInt(formData.get('quantity') as string),
                purpose: formData.get('purpose') as string,
                return_due_date: formData.get('due_date') as string
              }).then(() => closeIssueModal());
            }}>
              {/* Item Selector (Searchable Autocomplete) */}
              <div className="space-y-1.5 relative">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Item to Allocate</label>
                <div className="relative">
                  <input 
                    type="text"
                    className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold text-xs"
                    placeholder="Search item by name or code..."
                    value={itemSearchQuery}
                    onChange={e => {
                      setItemSearchQuery(e.target.value);
                      setSelectedItem(null);
                      setShowItemDropdown(true);
                    }}
                    onFocus={() => setShowItemDropdown(true)}
                    onBlur={() => setTimeout(() => setShowItemDropdown(false), 200)}
                    required
                  />
                  <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  {selectedItem && (
                    <CheckCircle2 className="absolute right-3.5 top-1/2 -translate-y-1/2 text-emerald-500 animate-in zoom-in-50" size={16} />
                  )}

                  {showItemDropdown && (
                    <div className="absolute z-40 top-full left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-xl max-h-48 overflow-y-auto divide-y divide-border/50 custom-scrollbar">
                      {items
                        .filter(i => 
                          i.name.toLowerCase().includes(itemSearchQuery.toLowerCase()) || 
                          (i.code || '').toLowerCase().includes(itemSearchQuery.toLowerCase())
                        )
                        .slice(0, 8)
                        .map(i => (
                          <button
                            key={i.id}
                            type="button"
                            onClick={() => {
                              setSelectedItem(i);
                              setItemSearchQuery(i.name);
                              setShowItemDropdown(false);
                            }}
                            className="w-full px-4 py-2.5 text-left hover:bg-muted/50 transition-colors"
                          >
                            <p className="text-xs font-bold text-text">{i.name}</p>
                            <p className="text-[0.6rem] text-text-muted">Code: {i.code || 'N/A'} • Stock: {i.total_stock || 0} {i.unit}</p>
                          </button>
                        ))
                      }
                      {items.filter(i => 
                        i.name.toLowerCase().includes(itemSearchQuery.toLowerCase()) || 
                        (i.code || '').toLowerCase().includes(itemSearchQuery.toLowerCase())
                      ).length === 0 && (
                        <p className="text-xs text-text-muted p-3 text-center">No matching items found</p>
                      )}
                    </div>
                  )}
                </div>
                <input type="hidden" name="item_id" value={selectedItem?.id || ''} />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Issue to</label>
                  <div className="relative">
                    <select 
                      name="to_type" 
                      value={issueToType} 
                      onChange={e => {
                        setIssueToType(e.target.value);
                        setSelectedIssuedToId('');
                        setUserSearchQuery('');
                        setTargetSearchQuery('');
                      }}
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold text-xs uppercase appearance-none"
                    >
                      <option value="staff">Staff / Teachers</option>
                      <option value="student">Student</option>
                      <option value="department">Department</option>
                      <option value="class">Class</option>
                      <option value="hostel">Hostel</option>
                      <option value="ground">Grounds</option>
                      <option value="kitchen">Kitchen per Hostel</option>
                      <option value="club">Club & Society</option>
                      <option value="sport">Sports Team</option>
                    </select>
                    <User className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none" size={16} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Quantity</label>
                  <div className="relative">
                    <input name="quantity" type="number" required className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                    <PackageCheck className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
              </div>

              {/* Target Entity Selector */}
              <div className="space-y-1.5 relative">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">
                  Target {issueToType === 'staff' ? 'Staff Member' : 
                          issueToType === 'student' ? 'Student' : 
                          issueToType === 'department' ? 'Department' :
                          issueToType === 'class' ? 'Class' :
                          issueToType === 'hostel' ? 'Hostel Building' :
                          issueToType === 'ground' ? 'Campus Ground' :
                          issueToType === 'club' ? 'Club & Society' :
                          issueToType === 'sport' ? 'Sports Team' :
                          'Hostel Kitchen'}
                </label>

                {/* Staff / Student Autocomplete Search */}
                {(issueToType === 'staff' || issueToType === 'student') && (
                  <div className="relative">
                    <input 
                      type="text"
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold"
                      placeholder={`Search name or email...`}
                      value={userSearchQuery}
                      onChange={e => {
                        setUserSearchQuery(e.target.value);
                        setSelectedIssuedToId('');
                        setShowUserDropdown(true);
                      }}
                      onFocus={() => setShowUserDropdown(true)}
                      onBlur={() => setTimeout(() => setShowUserDropdown(false), 200)}
                      required
                    />
                    <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                    {selectedIssuedToId && (
                      <CheckCircle2 className="absolute right-3.5 top-1/2 -translate-y-1/2 text-emerald-500 animate-in zoom-in-50" size={16} />
                    )}

                    {showUserDropdown && userSearchQuery && (
                      <div className="absolute z-30 top-full left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-xl max-h-48 overflow-y-auto divide-y divide-border/50 custom-scrollbar">
                        {usersList
                          .filter(u => u.role === (issueToType === 'staff' ? 'teacher' : 'student') || (issueToType === 'staff' && ['school_admin', 'systems_admin', 'principal', 'hr', 'bursar', 'librarian'].includes(u.role)))
                          .filter(u => `${u.first_name} ${u.last_name}`.toLowerCase().includes(userSearchQuery.toLowerCase()) || (u.email || '').toLowerCase().includes(userSearchQuery.toLowerCase()))
                          .slice(0, 5)
                          .map(u => (
                            <button
                              key={u.id}
                              type="button"
                              onClick={() => {
                                setSelectedIssuedToId(u.id);
                                setUserSearchQuery(`${u.first_name} ${u.last_name} (${u.role.toUpperCase()})`);
                                setShowUserDropdown(false);
                              }}
                              className="w-full px-4 py-2.5 text-left hover:bg-muted/50 transition-colors"
                            >
                              <p className="text-xs font-bold text-text">{u.first_name} {u.last_name}</p>
                              <p className="text-[0.6rem] text-text-muted">{u.email} • {u.role}</p>
                            </button>
                          ))
                        }
                      </div>
                    )}
                  </div>
                )}

                {/* Target Entity Autocomplete Search (for non-user types) */}
                {['class', 'department', 'hostel', 'ground', 'kitchen', 'club', 'sport'].includes(issueToType) && (
                  <div className="relative">
                    <input 
                      type="text"
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold"
                      placeholder={`Search ${issueToType}...`}
                      value={targetSearchQuery}
                      onChange={e => {
                        setTargetSearchQuery(e.target.value);
                        setSelectedIssuedToId('');
                        setShowTargetDropdown(true);
                      }}
                      onFocus={() => setShowTargetDropdown(true)}
                      onBlur={() => setTimeout(() => setShowTargetDropdown(false), 200)}
                      required
                    />
                    <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                    {selectedIssuedToId && (
                      <CheckCircle2 className="absolute right-3.5 top-1/2 -translate-y-1/2 text-emerald-500 animate-in zoom-in-50" size={16} />
                    )}

                    {showTargetDropdown && (
                      <div className="absolute z-30 top-full left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-xl max-h-48 overflow-y-auto divide-y divide-border/50 custom-scrollbar">
                        {(() => {
                          let list: any[] = [];
                          if (issueToType === 'class') list = classesList;
                          else if (issueToType === 'department') list = departmentsList;
                          else if (issueToType === 'hostel') list = hostelsList;
                          else if (issueToType === 'ground') list = groundsList;
                          else if (issueToType === 'kitchen') list = kitchensList;
                          else if (issueToType === 'club' || issueToType === 'sport') {
                            list = clubsList.filter(c => c.type === issueToType);
                          }

                          const filtered = list.filter(item => 
                            item.name.toLowerCase().includes(targetSearchQuery.toLowerCase())
                          );

                          if (filtered.length === 0) {
                            return <p className="text-xs text-text-muted p-3 text-center">No matching {issueToType}s found</p>;
                          }

                          return filtered.map(item => (
                            <button
                              key={item.id}
                              type="button"
                              onClick={() => {
                                setSelectedIssuedToId(item.id);
                                setTargetSearchQuery(item.name);
                                setShowTargetDropdown(false);
                              }}
                              className="w-full px-4 py-2.5 text-left hover:bg-muted/50 transition-colors"
                            >
                              <p className="text-xs font-bold text-text">{item.name}</p>
                            </button>
                          ));
                        })()}
                      </div>
                    )}
                  </div>
                )}
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Purpose / Notes</label>
                <div className="relative">
                  <input name="purpose" type="text" placeholder="e.g. Science Class Practical" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                  <ClipboardList className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none" size={16} />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">From Location</label>
                  <div className="relative">
                    <select name="store_id" required className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold appearance-none">
                      {locations.map(l => (
                        <option key={l.id} value={l.id}>{l.name}</option>
                      ))}
                    </select>
                    <MapPin className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none" size={16} />
                  </div>
                </div>

                <div className="space-y-1.5 relative">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Return Due (Optional)</label>
                  <div className="relative">
                    <input 
                      name="due_date" 
                      type="date" 
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold text-xs" 
                    />
                    <Calendar className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none" size={16} />
                  </div>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-4 bg-primary text-white rounded-2xl font-black uppercase tracking-[2px] text-xs shadow-lg shadow-primary/20 hover:scale-[1.02] active:scale-95 transition-all mt-4 shrink-0"
              >
                {loading ? 'Processing...' : 'Confirm Issue'}
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Return Modal */}
      {showReturnModal && selectedIssueForReturn && (
        <Modal
          open={true}
          onClose={() => setShowReturnModal(false)}
          title={`Return: ${selectedIssueForReturn.item_name}`}
          maxWidth="max-w-md"
          zIndex={100}
        >
          <ModalBody>
            <form id="inventory-return-form" className="space-y-6" onSubmit={handleReturnItemSubmit}>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Quantity to Return</label>
                  <div className="relative">
                    <input 
                      type="number" 
                      min="1" 
                      max={selectedIssueForReturn.quantity - selectedIssueForReturn.returned_quantity}
                      value={returnQuantity}
                      onChange={e => setReturnQuantity(Number(e.target.value))}
                      required 
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold" 
                    />
                    <Package className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Return Condition</label>
                  <div className="relative">
                    <select 
                      value={returnCondition}
                      onChange={e => setReturnCondition(e.target.value)}
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold text-xs uppercase appearance-none"
                    >
                      <option value="Good">Good</option>
                      <option value="Damaged">Damaged</option>
                      <option value="Lost">Lost</option>
                    </select>
                    <AlertTriangle className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Return to Location</label>
                <div className="relative">
                  <select 
                    value={returnLocation} 
                    onChange={e => setReturnLocation(e.target.value)}
                    required 
                    className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 font-bold appearance-none"
                  >
                    {locations.map(l => (
                      <option key={l.id} value={l.id}>{l.name}</option>
                    ))}
                  </select>
                  <MapPin className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-4 bg-emerald-500 text-white rounded-2xl font-black uppercase tracking-[2px] text-xs shadow-lg shadow-emerald-500/20 hover:scale-[1.02] active:scale-95 transition-all"
              >
                {loading ? 'Processing...' : 'Confirm Return'}
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Add Item Modal */}
      {showAddModal && (
        <Modal
          open={true}
          onClose={() => {
            setShowCustomCategoryInput(false);
            setShowCustomSupplierInput(false);
            setSelectedCategoryVal('');
            setSelectedSupplierVal('');
            setShowAddModal(false);
          }}
          title="Add New Item"
          maxWidth="max-w-md"
          zIndex={100}
        >
          <ModalBody>
            <form id="inventory-add-item-form" className="space-y-4" onSubmit={async (e) => {
              e.preventDefault();
              const formData = new FormData(e.currentTarget);
              try {
                let catId = parseInt(formData.get('category_id') as string);
                if (showCustomCategoryInput) {
                  const customCat = await createCategory({
                    name: formData.get('custom_category_name') as string,
                    code: formData.get('custom_category_code') as string
                  });
                  catId = customCat.id;
                }

                let supId = parseInt(formData.get('supplier_id') as string) || null;
                if (showCustomSupplierInput) {
                  const customSup = await createSupplier({
                    name: formData.get('custom_supplier_name') as string,
                    code: formData.get('custom_supplier_code') as string,
                    contact_person: formData.get('custom_supplier_contact') as string
                  });
                  supId = customSup.id;
                }

                await createItem({
                  name: formData.get('name') as string,
                  code: formData.get('code') as string,
                  barcode: formData.get('barcode') as string,
                  description: formData.get('description') as string,
                  category_id: catId,
                  unit: formData.get('unit') as string,
                  purchase_price: parseFloat(formData.get('purchase_price') as string) || 0,
                  selling_price: parseFloat(formData.get('selling_price') as string) || 0,
                  reorder_level: parseInt(formData.get('reorder_level') as string) || 10,
                  supplier_id: supId
                });

                setShowCustomCategoryInput(false);
                setShowCustomSupplierInput(false);
                setSelectedCategoryVal('');
                setSelectedSupplierVal('');
                setShowAddModal(false);
              } catch (err: any) {
                alert(err.message || 'Failed to save item');
              }
            }}>
              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Item Name</label>
                <div className="relative">
                  <input name="name" type="text" required placeholder="e.g. A4 Graph Books" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold font-sans font-bold" />
                  <Package className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Item Code</label>
                  <div className="relative">
                    <input name="code" type="text" placeholder="e.g. STAT-04" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                    <ClipboardList className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Unit of Measure</label>
                  <div className="relative">
                    <input name="unit" type="text" required placeholder="pcs, box, pack" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                    <Filter className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Category</label>
                  <div className="relative">
                    <select 
                      name="category_id" 
                      required={!showCustomCategoryInput}
                      value={selectedCategoryVal}
                      onChange={e => {
                        setSelectedCategoryVal(e.target.value);
                        setShowCustomCategoryInput(e.target.value === 'new_custom');
                      }}
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold text-xs appearance-none"
                    >
                      <option value="">Select Category...</option>
                      {categories.map(cat => (
                        <option key={cat.id} value={cat.id}>{cat.name}</option>
                      ))}
                      <option value="new_custom" className="text-primary font-bold">+ Add Custom Category...</option>
                    </select>
                    <LayoutGrid className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Supplier</label>
                  <div className="relative">
                    <select 
                      name="supplier_id"
                      value={selectedSupplierVal}
                      onChange={e => {
                        setSelectedSupplierVal(e.target.value);
                        setShowCustomSupplierInput(e.target.value === 'new_custom');
                      }}
                      className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold text-xs appearance-none"
                    >
                      <option value="">Select Supplier...</option>
                      {suppliers.map(sup => (
                        <option key={sup.id} value={sup.id}>{sup.name}</option>
                      ))}
                      <option value="new_custom" className="text-primary font-bold">+ Add Custom Supplier...</option>
                    </select>
                    <Building className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
              </div>

              {/* Custom Category Input Form */}
              {showCustomCategoryInput && (
                <div className="p-4 bg-primary/5 border border-primary/20 rounded-2xl space-y-4 animate-in slide-in-from-top-2 duration-200">
                  <p className="text-[0.65rem] font-black uppercase tracking-widest text-primary px-1">Create Custom Category</p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-bold uppercase tracking-wider text-text-muted px-1">Category Name</label>
                      <div className="relative">
                        <input name="custom_category_name" type="text" placeholder="e.g. Science Kits" required={showCustomCategoryInput} className="w-full px-4 py-2.5 pl-9 bg-background border border-border rounded-xl outline-none text-xs font-bold focus:border-primary focus:ring-2 focus:ring-primary/10" />
                        <Package className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={14} />
                      </div>
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-bold uppercase tracking-wider text-text-muted px-1">Category Code</label>
                      <div className="relative">
                        <input name="custom_category_code" type="text" placeholder="e.g. SCIE" required={showCustomCategoryInput} className="w-full px-4 py-2.5 pl-9 bg-background border border-border rounded-xl outline-none text-xs font-bold focus:border-primary focus:ring-2 focus:ring-primary/10" />
                        <ClipboardList className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={14} />
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Custom Supplier Input Form */}
              {showCustomSupplierInput && (
                <div className="p-4 bg-emerald-500/5 border border-emerald-500/20 rounded-2xl space-y-4 animate-in slide-in-from-top-2 duration-200">
                  <p className="text-[0.65rem] font-black uppercase tracking-widest text-emerald-600 px-1">Create Custom Supplier</p>
                  <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-bold uppercase tracking-wider text-text-muted px-1">Supplier Name</label>
                    <div className="relative">
                      <input name="custom_supplier_name" type="text" placeholder="e.g. Apex Wholesalers" required={showCustomSupplierInput} className="w-full px-4 py-2.5 pl-9 bg-background border border-border rounded-xl outline-none text-xs font-bold focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/10" />
                      <Building className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={14} />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-bold uppercase tracking-wider text-text-muted px-1">Supplier Code</label>
                      <div className="relative">
                        <input name="custom_supplier_code" type="text" placeholder="e.g. SUP04" className="w-full px-4 py-2.5 pl-9 bg-background border border-border rounded-xl outline-none text-xs font-bold focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/10" />
                        <ClipboardList className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={14} />
                      </div>
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-bold uppercase tracking-wider text-text-muted px-1">Contact Person</label>
                      <div className="relative">
                        <input name="custom_supplier_contact" type="text" placeholder="Contact name" className="w-full px-4 py-2.5 pl-9 bg-background border border-border rounded-xl outline-none text-xs font-bold focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/10" />
                        <User className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={14} />
                      </div>
                    </div>
                  </div>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Cost Price ($)</label>
                  <div className="relative">
                    <input name="purchase_price" type="number" step="0.01" placeholder="0.00" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                    <DollarSign className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Reorder Level</label>
                  <div className="relative">
                    <input name="reorder_level" type="number" defaultValue="10" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                    <AlertTriangle className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                  </div>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Barcode (Optional)</label>
                <div className="relative">
                  <input name="barcode" type="text" placeholder="Barcode number" className="w-full px-4 py-3 pl-10 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold" />
                  <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted px-1">Description</label>
                <textarea name="description" placeholder="Item description..." className="w-full px-4 py-3 bg-background border border-border rounded-2xl outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary font-bold text-sm h-20 resize-none" />
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-4 bg-primary text-white rounded-2xl font-black uppercase tracking-[2px] text-xs shadow-lg shadow-primary/20 hover:scale-[1.02] active:scale-95 transition-all mt-4 shrink-0"
              >
                {loading ? 'Adding...' : 'Add Item to Catalog'}
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}
