'use client';

import { useState, useEffect, useCallback } from 'react';
import { db, Item } from '@/lib/db';
import { inventoryApi } from '@/lib/api';
import { fetchAndCacheItems, syncOfflineOperations } from '@/lib/sync';
import Scanner from '@/components/Scanner';
import AIOnboarding from '@/components/AIOnboarding';
import PageShell from '@/components/PageShell';
import { toast } from 'react-hot-toast';
import {
  Package,
  Camera,
  Plus,
  Minus,
  Trash2,
  AlertTriangle,
  X,
  History,
  LayoutGrid,
  Wifi,
  WifiOff,
  ChevronRight,
  ChevronDown,
  Edit2,
  RefreshCw,
  CloudOff,
  Sparkles,
  Smartphone,
  CheckCircle2,
  User,
  ArrowDownCircle,
  ArrowUpCircle,
  Settings,
  Lock,
  Shield,
  Key,
  LogOut,
  UserPlus,
  Tag,
  ArrowRight,
  ArrowLeft,
  Search,
  Printer,
  Download
} from 'lucide-react';
import { generateBarcode128, getQRCodeURL } from '@/lib/labels';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import axios from 'axios';
import versionData from '../../VERSION.json';

interface User {
  id: number;
  username: string;
  role: string;
}

function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export default function Home() {
  const [mounted, setMounted] = useState(false);
  const [isOnline, setIsOnline] = useState(true);
  const [mode, setMode] = useState<'CHECK_IN' | 'CHECK_OUT' | 'TRASH'>('CHECK_OUT');
  const [showScanner, setShowScanner] = useState(false);
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [showBoxManager, setShowBoxManager] = useState(false);
  const [selectedBoxLabel, setSelectedBoxLabel] = useState<string | null>(null);
  const [selectedItem, setSelectedItem] = useState<Item | null>(null);
  const [boxMatches, setBoxMatches] = useState<Item[]>([]);
  const [isEditing, setIsEditing] = useState(false);
  const [isScannerReady, setIsScannerReady] = useState(false);
  const [editedItem, setEditedItem] = useState<Partial<Item>>({});
  const [adjustQty, setAdjustQty] = useState<number>(1);
  const [adjustType, setAdjustType] = useState<'ADD' | 'REMOVE' | 'TRASH'>('ADD');
  const [trashReason, setTrashReason] = useState('Damaged');
  const [lastScanned, setLastScanned] = useState<string | null>(null);
  const [inventory, setInventory] = useState<Item[]>([]);
  const [syncing, setSyncing] = useState(false);
  const [currentUser, setCurrentUser] = useState<any | null>(null);
  const [categories, setCategories] = useState<any[]>([]);
  const [fieldScanning, setFieldScanning] = useState<{ active: boolean, field: string } | null>(null);

  useEffect(() => {
    if (!localStorage.getItem('inventory_token')) {
      window.location.href = '/login';
      return;
    }
    setMounted(true);
    const savedUser = localStorage.getItem('inventory_user');
    if (savedUser) {
      setCurrentUser(JSON.parse(savedUser));
    }

    // Initial categories fetch
    inventoryApi.getCategories().then(c => setCategories(c)).catch(() => { });
  }, []);

  useEffect(() => {
    if (!localStorage.getItem('inventory_token')) {
      window.location.href = '/login';
      return;
    }
    setMounted(true);
    setIsOnline(navigator.onLine);
    const handleOnline = () => {
      setIsOnline(true);
      handleSync(); // Auto-sync pending ops when back online
    };
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Active polling for network status AND periodic background refresh (30s)
    const interval = setInterval(() => {
      setIsOnline(navigator.onLine);
      if (navigator.onLine) {
        loadInventory(); // Keep other devices in sync
      }
    }, 30000);

    loadInventory();
    preloadOCR();

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
      clearInterval(interval);
    };
  }, []);

  const loadInventory = async () => {
    const cached = await db.items.toArray();
    setInventory(cached);

    if (navigator.onLine) {
      const fresh = await fetchAndCacheItems();
      setInventory(fresh);
    }
  };

  const preloadOCR = async () => {
    try {
      // Import the library only when needed to keep bundle small
      const { createWorker } = await import('tesseract.js');
      const worker = await createWorker('eng');
      await worker.terminate();
      setIsScannerReady(true);
      console.log("OCR Engine Pre-warmed & Ready Offline");
    } catch (e) {
      console.warn("OCR Preload failed - will retry on demand", e);
    }
  };

  const handleOnboardingComplete = async (itemData: any) => {
    try {
      if (itemData.part_number) {
        itemData.part_number = itemData.part_number.toUpperCase();
      }
      // 1. Add to local DB cache
      await db.items.add(itemData);

      // 2. If online, try to push to backend immediately
      if (isOnline) {
        await inventoryApi.createItem(1, itemData);
        toast.success("Item saved to cloud catalog!");
      } else {
        toast.success("Item saved locally. Will sync when online.");
      }

      setShowOnboarding(false);
      await loadInventory();
    } catch (error) {
      console.error(error);
      toast.error("Failed to save item");
    }
  };

  const handleSync = useCallback(async () => {
    if (!isOnline || !currentUser) return;
    setSyncing(true);
    try {
      const result = await syncOfflineOperations(currentUser.id);
      if (result.success > 0) {
        toast.success(`Synced ${result.success} operations!`);
      }
      await loadInventory();
    } catch (error) {
      console.error("Sync failed", error);
    } finally {
      setSyncing(false);
    }
  }, [isOnline, currentUser]);

  const onScanSuccess = useCallback(async (barcode: string) => {
    setLastScanned(barcode);
    setShowScanner(false);

    const upperBarcode = barcode.toUpperCase();
    const item = await db.items.where('barcode').equals(barcode)
      .or('part_number').equals(upperBarcode).first();

    if (!item) {
      toast.error(`Item ${barcode} not found in catalog.`);
      return;
    }

    await db.pendingOperations.add({
      type: mode,
      barcode: item.barcode,
      quantity: 1,
      timestamp: Date.now(),
      synced: 0,
      uuid: crypto.randomUUID()
    });

    const newQty = mode === 'CHECK_IN' ? item.quantity + 1 : item.quantity - 1;
    await db.items.update(item.id!, { quantity: newQty });

    setInventory(prev => prev.map(i => i.id === item.id ? { ...i, quantity: newQty } : i));

    toast.success(`${mode === 'CHECK_IN' ? 'Checked in' : 'Checked out'} ${item.name}`);

    if (isOnline) {
      handleSync();
    }
  }, [mode, isOnline, handleSync]);

  const onOCRMatch = useCallback(async (text: string) => {
    // 1. Clean and normalize
    const cleanText = text.toUpperCase().replace(/[^A-Z0-9\s/+-]/g, ' ');

    // Garbage Filter: Ignore noisy strings (measurements like 0.11, dates like 2024-07-25)
    // We only keep tokens that are at least 3 chars AND not just decimals
    const tokens = cleanText.split(/[\s\n,]+/)
      .filter(t => t.length >= 3)
      .filter(t => !/^\d+\.\d+$/.test(t)) // Filter out decimals like 0.11 or 0.12
      .filter(t => !/^\d{2,4}-\d{2}-\d{2}$/.test(t)); // Filter out dates

    if (tokens.length === 0) return;

    // [NEW] Targeted Field Scan Logic
    if (fieldScanning?.active) {
      if (fieldScanning.field === 'box_label') {
        const potentialLabel = tokens[0] || cleanText;
        setEditedItem(prev => ({ ...prev, box_label: potentialLabel }));
        setFieldScanning(null);
        toast.success(`Captured: ${potentialLabel}`);
        return;
      }
    }

    // Toast only potentially useful scans
    toast(`Scanning: ${cleanText.substring(0, 30)}...`, { icon: '🔍', duration: 1500, id: 'ocr-scan' });

    // [BOX SCANNING LOGIC] Prioritize checking if this is a known box
    const possibleBoxItems = inventory.filter(item => {
      if (!item.box_label) return false;
      const boxText = item.box_label.toUpperCase().replace(/[^A-Z0-9\s/+-]/g, ' ');
      // Exact or Partial include match for box label
      if (cleanText.includes(boxText)) return true;
      // Strong token matching (for words >= 4 chars)
      const boxTokens = boxText.split(/[\s/+-]/).filter(t => t.length >= 4);
      const matchedTokens = boxTokens.filter(bt => tokens.includes(bt));
      return matchedTokens.length >= 2 || (boxTokens.length === 1 && matchedTokens.length === 1);
    });

    if (possibleBoxItems.length === 1) {
      toast.success(`Box identified: 1 item found`, { duration: 3000, id: 'ocr-success' });
      setSelectedItem(possibleBoxItems[0]);
      setAdjustType(mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
      setShowScanner(false);
      return;
    } else if (possibleBoxItems.length > 1) {
      toast.success(`Box identified: ${possibleBoxItems.length} items found`, { duration: 3000, id: 'ocr-success' });
      setBoxMatches(possibleBoxItems);
      setShowScanner(false);
      return;
    }

    // [INDIVIDUAL ITEM MATCHING] Fallback to classic specific identification
    let bestMatch = null;
    let maxMatchScore = 0;

    for (const item of inventory) {
      let score = 0;
      const pn = (item.part_number || '').toUpperCase();
      const sn = (item.serial_number || '').toUpperCase();
      const name = item.name.toUpperCase();
      const category = item.category.toUpperCase();

      // Priority 1: Serial Number (Absolute match)
      if (sn && cleanText.includes(sn)) score += 500;

      // Priority 2: Part Number (High confidence)
      if (pn && cleanText.includes(pn)) score += 200;

      // Priority 3: Token based matching for PN (LC/UPC etc)
      if (pn) {
        const pnTokens = pn.split(/[\s/+-]/).filter(t => t.length >= 3);
        pnTokens.forEach(t => { if (cleanText.includes(t)) score += 50; });
      }

      // Priority 4: Name & Category
      const nameTokens = name.split(/[\s/+-]/).filter(t => t.length >= 3);
      nameTokens.forEach(t => { if (cleanText.includes(t)) score += 10; });

      if (category && cleanText.includes(category)) score += 20;

      if (score > maxMatchScore) {
        maxMatchScore = score;
        bestMatch = item;
      }
    }

    // Threshold: Need a significant score to match automatically
    if (bestMatch && maxMatchScore >= 40) {
      toast.success(`Matched: ${bestMatch.name}`, { duration: 3000, id: 'ocr-success' });
      setSelectedItem(bestMatch);
      setAdjustType(mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
      setShowScanner(false);
    }
  }, [mode, inventory]);

  const handleUpdateItem = async () => {
    if (!selectedItem) return;
    try {
      const updated = { ...selectedItem, ...editedItem };
      // Normalize PN
      if (updated.part_number) updated.part_number = updated.part_number.toUpperCase();

      await db.items.update(selectedItem.id!, updated);

      if (isOnline) {
        await inventoryApi.updateItem(selectedItem.id!, updated);
      }

      toast.success("Item updated successfully");
      setIsEditing(false);
      setSelectedItem(updated as Item);
      await loadInventory();
    } catch (err) {
      console.error(err);
      toast.error("Failed to update item");
    }
  };

  const handleDeleteItem = async () => {
    if (!selectedItem || !selectedItem.id) return;
    if (!window.confirm(`Are you sure you want to delete "${selectedItem.name}" completely from the catalog?`)) return;

    try {
      await db.items.delete(selectedItem.id);
      if (isOnline) {
        await inventoryApi.deleteItem(selectedItem.id);
      }
      toast.success("Item deleted from catalog");
      setSelectedItem(null);
      await loadInventory();
    } catch (err) {
      console.error(err);
      toast.error("Failed to delete item");
    }
  };

  const handleAdjustStock = async () => {
    if (!selectedItem) return;

    const toastId = toast.loading("Processing...");

    try {
      const finalAdjustQty = adjustQty;
      const newQty = selectedItem.quantity + (adjustType === 'ADD' ? adjustQty : -adjustQty);

      // 1. Create a unique ID for this operation to prevent double-counting on server
      const operationId = crypto.randomUUID();

      // 2. Queue local operation
      const opType = adjustType === 'ADD' ? 'CHECK_IN' : (adjustType === 'TRASH' ? 'TRASH' : 'CHECK_OUT');

      await db.pendingOperations.add({
        type: opType as any,
        barcode: selectedItem.barcode,
        quantity: finalAdjustQty,
        timestamp: Date.now(),
        synced: 0,
        // We add this to our DB even if it doesn't have it yet, Dexie handles it
        uuid: operationId
      } as any);

      // 3. Update local UI & DB
      await db.items.update(selectedItem.id!, { quantity: newQty });
      setInventory(prev => prev.map(i => i.id === selectedItem.id ? { ...i, quantity: newQty } : i));

      // 4. Trigger Sync
      if (isOnline) {
        await handleSync();
        toast.success("Inventory updated & synced", { id: toastId });
      } else {
        toast.success("Saved locally (Offline)", { id: toastId });
      }

      setSelectedItem(null);
      setAdjustQty(1);
    } catch (error: any) {
      console.error("Adjustment failure:", error);
      toast.error("Error saving operation", { id: toastId });
    }
  };

  const [searchQuery, setSearchQuery] = useState('');

  const filteredInventory = inventory.filter(item => {
    const query = searchQuery.toLowerCase();
    return (
      item.name.toLowerCase().includes(query) ||
      item.category.toLowerCase().includes(query) ||
      (item.specs?.toLowerCase().includes(query) ?? false) ||
      (item.part_number?.toLowerCase().includes(query) ?? false) ||
      (item.color?.toLowerCase().includes(query) ?? false) ||
      (item.box_label?.toLowerCase().includes(query) ?? false)
    );
  });

  // Extract unique item types and box labels for suggestions
  const existingTypes = Array.from(new Set(inventory.map(i => i.type).filter(Boolean))).sort() as string[];
  const existingBoxes = Array.from(new Set(inventory.map(i => i.box_label).filter(Boolean))).sort() as string[];

  if (!mounted) return null;

  return (
    <PageShell>
      <div className="p-3 md:p-8 overflow-x-hidden w-full max-w-7xl mx-auto">
        {/* Search datalists for autocomplete */}
      <datalist id="existing-types">
        {existingTypes.map(t => <option key={t} value={t} />)}
      </datalist>
      <datalist id="existing-boxes">
        {existingBoxes.map(b => <option key={b} value={b} />)}
      </datalist>

        {/* Header */}
        <header className="flex flex-col sm:flex-row justify-between sm:items-center gap-4 mb-6 w-full px-1">
          <div className="flex items-center gap-3">
            <div className="p-1">
              <img
                src="/logo.png"
                alt="TFM aInventory"
                className="h-8 md:h-10 object-contain drop-shadow-xl rounded-lg"
              />
            </div>
            <div>
              <h1 className="text-lg md:text-xl font-black tracking-normal text-white leading-none">
                TFM <span className="font-mono text-primary bg-primary/5 px-2 py-0.5 rounded-lg border border-primary/10 ml-1">aInventory</span>
              </h1>
              <div className="flex items-center gap-2 mt-1">
                <p className="text-xs font-bold text-slate-500 font-mono">
                  Version {versionData.version}
                </p>
                <span className="w-1 h-1 rounded-full bg-slate-800" />
                <button
                  className="text-xs font-black text-primary/80 hover:text-primary transition-colors flex items-center gap-1"
                >
                  <User size={8} />
                  {currentUser?.username || 'Guest'}
                </button>
              </div>
            </div>
          </div>

          <div className="flex flex-wrap items-center justify-between sm:justify-end gap-3 sm:gap-6 bg-slate-900/40 sm:bg-transparent p-3 sm:p-0 rounded-2xl border border-slate-800/50 sm:border-none">
            <div className="flex flex-wrap items-center gap-4">
              {isScannerReady && (
                <div className="flex items-center gap-1.5">
                  <div className="w-1 h-1 rounded-full bg-green-500 shadow-[0_0_5px_rgba(34,197,94,0.5)]" />
                  <span className="text-xs font-black text-green-500/80 whitespace-nowrap">
                    Offline Scan: OK
                  </span>
                </div>
              )}
              <div className="flex items-center gap-1.5">
                <div className={`w-1 h-1 rounded-full ${isOnline ? 'bg-green-500 animate-pulse shadow-[0_0_5px_rgba(34,197,94,0.5)]' : 'bg-rose-500 shadow-[0_0_5px_rgba(244,63,94,0.5)]'}`} />
                <span className={`text-xs font-black whitespace-nowrap ${isOnline ? 'text-green-500/80' : 'text-rose-500/80'}`}>
                  Server Sync: {isOnline ? 'OK' : 'No'}
                </span>
              </div>
            </div>
            <div className="flex items-center gap-2">
            <button 
              onClick={() => setShowBoxManager(true)}
              className="p-3 bg-slate-900 border border-slate-800 text-slate-400 rounded-xl hover:text-primary transition-colors hover:border-primary/30"
              title="Box Manager"
            >
              <Package size={20} />
            </button>
            <button 
              onClick={handleSync} 
              disabled={syncing}
              className="p-3 bg-slate-900 border border-slate-800 text-slate-400 rounded-xl hover:text-white transition-colors disabled:opacity-50"
            >
              <RefreshCw size={20} className={syncing ? "animate-spin text-primary" : ""} />
            </button>
          </div>
          </div>
        </header>

        <div className="w-full px-1 space-y-6">
          {/* Mode Switcher */}
          <div className="flex p-1 bg-slate-900/80 backdrop-blur-md rounded-2xl shadow-inner w-full">
            {[
              { id: 'CHECK_IN', label: 'Check in', icon: ArrowDownCircle },
              { id: 'CHECK_OUT', label: 'Check out', icon: ArrowUpCircle },
              { id: 'TRASH', label: 'Trash', icon: Trash2 }
            ].map((m) => (
              <button
                key={m.id}
                onClick={() => setMode(m.id as any)}
                className={cn(
                  "flex-1 py-3 rounded-xl text-sm font-black transition-all flex items-center justify-center gap-2",
                  mode === m.id ? "bg-slate-800 text-primary shadow-lg" : "text-slate-500 hover:text-slate-300"
                )}
              >
                <m.icon size={18} />
                {m.label}
              </button>
            ))}
          </div>

          {/* Scanner Section */}
          <section className="glass-card rounded-3xl p-6">
            {showScanner ? (
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <h2 className="text-lg font-semibold">Scanning...</h2>
                  <button
                    onClick={() => setShowScanner(false)}
                    className="text-sm text-slate-400 hover:text-white"
                  >
                    Cancel
                  </button>
                </div>
                <Scanner onScanSuccess={onScanSuccess} onOCRMatch={onOCRMatch} />
              </div>
            ) : (
              <div className="flex flex-col items-center py-8 text-center gap-6">
                <button
                  onClick={() => setShowScanner(true)}
                  className="w-24 h-24 rounded-full bg-primary/20 hover:bg-primary/30 border-2 border-primary border-dashed flex items-center justify-center group transition-all"
                >
                  <Smartphone className="w-10 h-10 text-primary group-hover:scale-110 transition-transform" />
                </button>

                <div>
                  <p className="text-lg font-medium">Tap to start scanning</p>
                  <p className="text-sm text-slate-400">Scan labels to {mode.replace('_', ' ')} items</p>
                </div>

                <div className="w-full h-px bg-slate-800 my-2" />

                <button
                  onClick={() => setShowOnboarding(true)}
                  className="w-full h-16 rounded-[1.5rem] bg-slate-900/50 border border-slate-800 flex items-center justify-center gap-3 group hover:border-primary/40 transition-all font-bold"
                >
                  <Sparkles size={18} className="text-primary group-hover:scale-110 transition-transform" />
                  <span className="text-sm">Add NEW Item<br />(AI Onboarding)</span>
                </button>
              </div>
            )}
          </section>
        </div>

        {/* Onboarding Overlay */}
        {showOnboarding && (
          <AIOnboarding
            categories={categories}
            inventory={inventory}
            onCancel={() => setShowOnboarding(false)}
            onComplete={handleOnboardingComplete}
          />
        )}

        {/* Stock Adjustment Overlay */}
        {selectedItem && (
          <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm animate-in fade-in duration-200">
            <div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-[2.5rem] shadow-2xl p-6 overflow-hidden animate-in slide-in-from-bottom-10 duration-300">
              <div className="flex justify-between items-center mb-6">
                {isEditing ? (
                  <h3 className="text-xl font-black tracking-tight">Edit Metadata</h3>
                ) : (
                  <h3 className="text-xl font-black tracking-tight">{selectedItem.name}</h3>
                )}
                <div className="flex gap-2">
                  {!isEditing && (
                    <button
                      onClick={() => {
                        setEditedItem(selectedItem);
                        setIsEditing(true);
                      }}
                      className="p-2 hover:bg-slate-800 rounded-full text-slate-400"
                    >
                      <Edit2 size={20} />
                    </button>
                  )}
                  {isEditing && (
                    <button
                      onClick={handleDeleteItem}
                      className="p-2 hover:bg-red-500/20 rounded-full text-red-500"
                    >
                      <Trash2 size={20} />
                    </button>
                  )}
                  <button
                    onClick={() => {
                      setSelectedItem(null);
                      setIsEditing(false);
                    }}
                    className="p-2 hover:bg-slate-800 rounded-full"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              {isEditing ? (
                <div className="space-y-4 mb-8">
                  <div>
                    <label className="text-xs font-black text-slate-500 ml-1">Name</label>
                    <input
                      type="text"
                      value={editedItem.name || ''}
                      onChange={e => setEditedItem({ ...editedItem, name: e.target.value })}
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-100"
                    />
                  </div>
                  <div>
                    <label className="text-xs font-black text-slate-500 ml-1">Part Number (for OCR match)</label>
                    <input
                      type="text"
                      value={editedItem.part_number || ''}
                      onChange={e => setEditedItem({ ...editedItem, part_number: e.target.value })}
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm font-mono outline-none text-slate-100"
                      placeholder="e.g. OM4-TURQ-2M"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-xs font-black text-slate-500 ml-1">Category</label>
                      <div className="relative flex items-center">
                        <select
                          value={editedItem.category || ''}
                          onChange={e => setEditedItem({ ...editedItem, category: e.target.value })}
                          className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-100 appearance-none"
                        >
                          <option value="">Select Category</option>
                          {categories.map(c => (
                            <option key={c.id} value={c.name}>{c.name}</option>
                          ))}
                        </select>
                        <ChevronDown size={16} className="absolute right-4 text-slate-500 pointer-events-none" />
                      </div>
                    </div>
                    <div>
                      <label className="text-xs font-black text-slate-500 ml-1">Item Type (e.g. SFP, Patch Cord)</label>
                      <input 
                        type="text" 
                        list="existing-types"
                        value={editedItem.type || ''} 
                        onChange={e => setEditedItem({...editedItem, type: e.target.value})}
                        className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-100"
                        placeholder="e.g. SFP+"
                      />
                    </div>
                    <div className="col-span-2">
                       <label className="text-xs font-black text-slate-500 ml-1">Box / Container Label</label>
                       <div className="relative flex items-center">
                         <input 
                           type="text" 
                           list="existing-boxes"
                           value={editedItem.box_label || ''} 
                           onChange={e => setEditedItem({...editedItem, box_label: e.target.value})}
                           className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 pl-4 pr-12 text-sm outline-none text-slate-100 placeholder:text-slate-700 focus:border-primary transition-colors"
                           placeholder="e.g. SFPs 40G Cisco"
                         />
                         <button 
                           type="button"
                           onClick={() => {
                             setFieldScanning({ active: true, field: 'box_label' });
                             setShowScanner(true);
                             toast.success("Scanning for BOX label...");
                           }}
                           className={cn(
                             "absolute right-2 p-2 rounded-lg transition-all",
                             fieldScanning?.active ? "bg-primary text-white animate-pulse" : "text-slate-500 hover:bg-slate-800"
                           )}
                         >
                           <Camera size={18} />
                         </button>
                       </div>
                    </div>
                    <div className="col-span-2">
                      <label className="text-xs font-black text-slate-500 ml-1">Specs</label>
                      <input
                        type="text"
                        value={editedItem.specs || ''}
                        onChange={e => setEditedItem({ ...editedItem, specs: e.target.value })}
                        className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-100"
                      />
                    </div>
                  </div>
                </div>
              ) : (
                <>

                  <div className="flex p-1 bg-slate-950 rounded-2xl mb-8">
                    {[
                      { id: 'ADD', label: 'Buy More', icon: Plus, color: 'text-primary' },
                      { id: 'REMOVE', label: 'Subtract', icon: Minus, color: 'text-amber-500' },
                      { id: 'TRASH', label: 'Discard', icon: Trash2, color: 'text-red-500' }
                    ].map((t) => (
                      <button
                        key={t.id}
                        onClick={() => setAdjustType(t.id as any)}
                        className={cn(
                          "flex-1 flex flex-col items-center py-3 rounded-xl transition-all",
                          adjustType === t.id ? "bg-slate-800 shadow-lg" : "text-slate-500"
                        )}
                      >
                        <t.icon size={20} className={adjustType === t.id ? t.color : ""} />
                        <span className="text-xs font-black mt-1">{t.label}</span>
                      </button>
                    ))}
                  </div>

                  <div className="flex flex-col items-center gap-6 mb-8">
                    <div className="flex items-center gap-8">
                      <button
                        onClick={() => setAdjustQty(Math.max(1, adjustQty - 1))}
                        className="w-12 h-12 rounded-full border border-slate-800 flex items-center justify-center text-slate-400 active:bg-slate-800"
                      >
                        <Minus size={24} />
                      </button>
                      <div className="text-center">
                        <span className="text-5xl font-black tabular-nums">{adjustQty}</span>
                      </div>
                      <button
                        onClick={() => setAdjustQty(adjustQty + 1)}
                        className="w-12 h-12 rounded-full border border-slate-800 flex items-center justify-center text-slate-400 active:bg-slate-800"
                      >
                        <Plus size={24} />
                      </button>
                    </div>

                    {adjustType === 'TRASH' && (
                      <div className="w-full bg-red-500/5 border border-red-500/20 p-4 rounded-2xl animate-in shake duration-500">
                        <div className="flex items-center gap-2 mb-3">
                          <AlertTriangle size={16} className="text-red-500" />
                          <span className="text-sm font-bold text-red-400">Waste Declaration</span>
                        </div>
                        <select
                          value={trashReason}
                          onChange={(e) => setTrashReason(e.target.value)}
                          className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-300"
                        >
                          <option>Damaged</option>
                          <option>Expired</option>
                          <option>Lost</option>
                          <option>Technical Failure</option>
                          <option>Other</option>
                        </select>
                      </div>
                    )}
                  </div>
                </>
              )}

              <button
                onClick={isEditing ? handleUpdateItem : handleAdjustStock}
                className={cn(
                  "w-full py-5 rounded-[1.8rem] font-black text-lg transition-all active:scale-[0.98] shadow-2xl",
                  isEditing ? "bg-slate-100 text-slate-900" : (
                    adjustType === 'ADD' ? "bg-primary shadow-primary/20 text-white" :
                      adjustType === 'REMOVE' ? "bg-amber-600 shadow-amber-500/20 text-white" :
                        "bg-red-600 shadow-red-500/20 text-white"
                  )
                )}
              >
                {isEditing ? "Save Changes" : (
                  adjustType === 'ADD' ? `Add ${adjustQty} to Stock` :
                    adjustType === 'REMOVE' ? `Subtract ${adjustQty} from Stock` :
                      `Discard ${adjustQty} items`
                )}
              </button>
            </div>
          </div>
        )}


        {/* Box Contents Selection Modal */}
      {boxMatches.length > 0 && !selectedItem && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm animate-in fade-in duration-200">
          <div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-[2.5rem] shadow-2xl p-6 overflow-hidden animate-in slide-in-from-bottom-10 duration-300 flex flex-col max-h-[85vh]">
            <div className="flex justify-between items-center mb-6 shrink-0">
              <div>
                <h3 className="text-xl font-black tracking-tight flex items-center gap-2">
                  <Package className="text-primary" />
                  Box Contents
                </h3>
                <p className="text-xs text-slate-400 font-bold mt-1">Select the item you want to {mode.replace('_', ' ').toLowerCase()}</p>
              </div>
              <button onClick={() => setBoxMatches([])} className="p-2 hover:bg-slate-800 rounded-full">
                <X size={20} />
              </button>
            </div>
            
            <div className="overflow-y-auto w-full pr-2 space-y-3 pb-4">
              {boxMatches.map(item => (
                <button
                  key={item.id}
                  onClick={() => {
                    setSelectedItem(item);
                    setBoxMatches([]);
                    setAdjustType(mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
                  }}
                  className="w-full text-left bg-slate-950/50 hover:bg-slate-800 border border-slate-800/80 p-4 rounded-2xl flex items-center gap-4 transition-all active:scale-[0.98] group"
                >
                  <div className="flex-1 min-w-0">
                     <p className="text-sm font-black text-white group-hover:text-primary transition-colors truncate">{item.name}</p>
                     <div className="flex items-center gap-2 mt-1">
                        <span className="text-[10px] font-mono text-slate-500">{item.part_number}</span>
                        <span className="w-1 h-1 rounded-full bg-slate-800" />
                        <span className="text-[10px] font-bold text-slate-400">Stock: {item.quantity}</span>
                     </div>
                  </div>
                  <ChevronRight size={18} className="text-slate-600 group-hover:text-primary" />
                </button>
              ))}
            </div>
            <button 
              onClick={() => setBoxMatches([])}
              className="w-full py-4 mt-2 rounded-[1.5rem] font-black text-sm bg-slate-800 text-white hover:bg-slate-700 transition-colors shrink-0"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Box Manager Modal */}
      {showBoxManager && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/90 backdrop-blur-md animate-in fade-in duration-300">
          <div className="w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-[2.5rem] shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
            <div className="p-8 border-b border-slate-800 flex justify-between items-center shrink-0 bg-slate-900/50">
               <div>
                  <h3 className="text-2xl font-black tracking-tight flex items-center gap-3">
                    <Package className="text-primary" size={28} />
                    Box Inventory
                  </h3>
                  <p className="text-sm text-slate-500 font-bold mt-1">Manage physical box labels & printing</p>
               </div>
               <button onClick={() => setShowBoxManager(false)} className="p-3 hover:bg-slate-800 rounded-full transition-colors">
                  <X size={24} />
               </button>
            </div>

            <div className="flex-1 overflow-y-auto p-6 space-y-4">
               {existingBoxes.length === 0 ? (
                 <div className="py-20 text-center space-y-4 opacity-40">
                    <Package size={48} className="mx-auto" />
                    <p className="font-bold">No box labels defined yet.</p>
                    <p className="text-xs max-w-xs mx-auto">Associate items with a "Box Label" in their metadata to see them here.</p>
                 </div>
               ) : (
                 <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {existingBoxes.map(box => {
                      const itemCount = inventory.filter(i => i.box_label === box).length;
                      return (
                        <div key={box} className="bg-slate-950 border border-slate-800 p-5 rounded-3xl flex flex-col gap-4 group hover:border-primary/50 transition-all">
                           <div className="flex-1 min-w-0">
                              <h4 className="text-lg font-black text-white truncate">{box}</h4>
                              <p className="text-xs text-slate-500 font-bold">{itemCount} items linked</p>
                           </div>
                           <div className="flex gap-2 shrink-0">
                              <button 
                                onClick={() => setSelectedBoxLabel(box)}
                                className="flex-1 py-3 bg-primary text-white text-xs font-black rounded-xl flex items-center justify-center gap-2 hover:bg-blue-500 transition-colors shadow-lg shadow-primary/20"
                              >
                                <Printer size={14} /> Print Label
                              </button>
                              <button 
                                onClick={() => { setQuery(box.toLowerCase()); setShowBoxManager(false); }}
                                className="px-4 py-3 bg-slate-900 border border-slate-800 text-slate-400 text-xs font-bold rounded-xl hover:bg-slate-800"
                              >
                                View
                              </button>
                           </div>
                        </div>
                      );
                    })}
                 </div>
               )}
            </div>
            
            <div className="p-6 bg-slate-950/50 border-t border-slate-800 text-center">
               <p className="text-[10px] text-slate-600 font-bold uppercase tracking-widest">TFM aInventory • Box Management Mode</p>
            </div>
          </div>
        </div>
      )}

      {/* Label Print Preview Modal */}
      {selectedBoxLabel && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/95 animate-in zoom-in-95 duration-200">
           <div className="w-full max-w-md flex flex-col gap-6">
              
              <div id="print-label-area" className="w-full bg-white p-8 rounded-lg shadow-2xl flex flex-col items-center gap-6">
                 <h2 className="text-2xl font-black text-black tracking-tighter text-center uppercase">
                   {selectedBoxLabel}
                 </h2>
                 
                 <div className="w-full aspect-[2/1] bg-white flex flex-col items-center justify-center overflow-hidden" dangerouslySetInnerHTML={{ __html: generateBarcode128(selectedBoxLabel) }} />
                 
                 <div className="flex flex-col items-center gap-1">
                    <p className="text-[10px] font-black tracking-[0.2em] text-black/50">TFM INVENTORY BOX LABEL</p>
                    <img src={getQRCodeURL(selectedBoxLabel)} className="w-24 h-24" alt="QR Code" />
                 </div>
              </div>

              <div className="flex flex-col gap-3 no-print">
                 <button 
                   onClick={() => window.print()}
                   className="w-full py-5 bg-primary text-white rounded-[2rem] font-black text-lg flex items-center justify-center gap-3 shadow-2xl shadow-primary/40 active:scale-95 transition-all"
                 >
                   <Printer size={20} /> Print to Dymo/Brother
                 </button>
                 
                 <button 
                    onClick={() => {
                        const svg = document.querySelector("#print-label-area svg");
                        if (svg) {
                            const svgData = new XMLSerializer().serializeToString(svg);
                            const canvas = document.createElement("canvas");
                            const ctx = canvas.getContext("2d");
                            const img = new Image();
                            img.onload = () => {
                                canvas.width = img.width * 4;
                                canvas.height = img.height * 4;
                                if (ctx) {
                                    ctx.fillStyle = "white";
                                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                                    const link = document.createElement("a");
                                    link.download = `Label-${selectedBoxLabel}.png`;
                                    link.href = canvas.toDataURL("image/png");
                                    link.click();
                                }
                            };
                            img.src = "data:image/svg+xml;base64," + btoa(svgData);
                        }
                    }}
                    className="w-full py-4 bg-slate-900 border border-slate-800 text-white rounded-[2rem] font-black text-sm flex items-center justify-center gap-2 active:scale-95 transition-all"
                 >
                    <Download size={16} /> Save for Mobile App
                 </button>
                 
                 <button 
                   onClick={() => setSelectedBoxLabel(null)}
                   className="w-full py-4 text-slate-500 font-bold text-xs"
                 >
                   Cancel
                 </button>
              </div>

              {/* Print CSS Injection */}
              <style dangerouslySetInnerHTML={{ __html: `
                @media print {
                  body * { display: none !important; }
                  #print-label-area { 
                    display: flex !important; 
                    position: fixed !important;
                    top: 0 !important;
                    left: 0 !important;
                    width: 100% !important;
                    height: 100% !important;
                    margin: 0 !important;
                    padding: 40px !important;
                    border: none !important;
                    box-shadow: none !important;
                  }
                  .no-print { display: none !important; }
                }
                @page {
                  size: auto;
                  margin: 0;
                }
              `}} />
           </div>
        </div>
      )}

      {/* Footer Branding */}
        <footer className="mt-20 mb-8 flex flex-col items-center gap-2 opacity-30">
          <p className="text-xs font-bold">Powered by TFM Group Software</p>
          <div className="h-px w-12 bg-slate-800" />
          <p className="text-[9px] font-mono">v{versionData.version} • {versionData.last_build} • BUILD: dev-{versionData.commit}</p>
        </footer>
      </div>
    </PageShell>
  );
}
