'use client';

import { useState, useEffect, useCallback } from 'react';
import { db, Item } from '@/lib/db';
import { inventoryApi, getBackendUrl } from '@/lib/api';
import PageShell from '@/components/PageShell';
import Scanner from '@/components/Scanner';
import StatCard from '@/components/StatCard';
import InventoryTable from '@/components/InventoryTable';
import FilterBar from '@/components/FilterBar';
import SearchModal from '@/components/inventory/SearchModal';
import QuantityAdjustmentModal from '@/components/inventory/QuantityAdjustmentModal';
import { useInventoryFilter } from '@/hooks/useInventoryFilter';
import { toast } from 'react-hot-toast';
import {
  Package,
  Layers,
  X,
  Edit2,
  Camera,
  Layout,
  Printer,
  Download,
  Box,
  Search
} from 'lucide-react';
import { generateBarcode128, getQRCodeURL } from '@/lib/labels';
import { cn } from '@/lib/utils';
import versionData from '../VERSION.json';

export default function InventoryPage() {
  const [mounted, setMounted] = useState(false);
  const [inventory, setInventory] = useState<Item[]>([]);
  const [stats, setStats] = useState<any>(null);
  const [currentUser, setCurrentUser] = useState<any | null>(null);
  const [backendUrl, setBackendUrl] = useState<string>('');

  const {
    searchQuery,
    setSearchQuery,
    expandedCategory,
    setExpandedCategory,
    boxSearchQuery,
    setBoxSearchQuery,
    categories,
    filteredCategories,
    getFilteredItems,
    getFilteredBoxes
  } = useInventoryFilter(inventory);
  
  // Stock Adjustment State
  const [selectedItem, setSelectedItem] = useState<Item | null>(null);
  const [adjustQty, setAdjustQty] = useState<number>(1);
  const [adjustType, setAdjustType] = useState<'ADD' | 'REMOVE' | 'TRASH'>('ADD');
  const [trashReason, setTrashReason] = useState('Damaged');

  // Item Editing state
  const [isEditing, setIsEditing] = useState(false);
  const [editedItem, setEditedItem] = useState<Partial<Item>>({});
  const [categoriesList, setCategoriesList] = useState<any[]>([]);

  // Category Editing state
  const [editingCategory, setEditingCategory] = useState<any | null>(null);
  const [catEditedName, setCatEditedName] = useState('');
  const [catEditedDesc, setCatEditedDesc] = useState('');

  // Scanner state
  const [showScanner, setShowScanner] = useState(false);
  const [fieldScanning, setFieldScanning] = useState<{ active: boolean, field: string } | null>(null);

  // Box Manager State
  const [showBoxManager, setShowBoxManager] = useState(false);
  const [selectedBoxLabel, setSelectedBoxLabel] = useState<string | null>(null);

  // Search Modal State
  const [showSearchModal, setShowSearchModal] = useState(false);
  const [selectedSearchItem, setSelectedSearchItem] = useState<Item | null>(null);
  const [showQuantityModal, setShowQuantityModal] = useState(false);

  useEffect(() => {
    setMounted(true);
    const savedUser = localStorage.getItem('inventory_user');
    if (savedUser) {
      setCurrentUser(JSON.parse(savedUser));
    }

    getBackendUrl().then(setBackendUrl);
    loadData();
  }, []);

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

    try {
      const s = await inventoryApi.getStats();
      setStats(s);
      
      const cats = await inventoryApi.getCategories();
      setCategoriesList(cats);

      const res = await inventoryApi.getItems();
      setInventory(res);
      await db.items.clear();
      await db.items.bulkPut(res);
    } catch (err: any) {
      console.error("Failed to load backend data", err);
    }
  };

  const handleAdjustStock = async () => {
    if (!selectedItem) return;
    const toastId = toast.loading("Processing...");
    
    try {
      const isOnline = navigator.onLine;
      const finalAdjustQty = adjustQty;
      const newQty = selectedItem.quantity + (adjustType === 'ADD' ? adjustQty : -adjustQty);

      await db.items.update(selectedItem.id!, { quantity: newQty });
      setInventory(prev => prev.map(i => i.id === selectedItem.id ? { ...i, quantity: newQty } : i));
      
      if (isOnline) {
        const endpoint = adjustType === 'ADD' ? 'check-in' : (adjustType === 'TRASH' ? 'trash' : 'check-out');
        const payload: any = {
           barcode: selectedItem.barcode,
           quantity: finalAdjustQty,
           user_id: currentUser?.id || 1
        };
        if (adjustType === 'TRASH') payload.reason = trashReason;
        
        await inventoryApi.adjustStock(endpoint, payload);
        toast.success("Inventory updated & synced", { id: toastId });
      } else {
        await db.pendingOperations.add({
          type: adjustType === 'ADD' ? 'CHECK_IN' : (adjustType === 'TRASH' ? 'TRASH' : 'CHECK_OUT'),
          barcode: selectedItem.barcode,
          quantity: finalAdjustQty,
          timestamp: Date.now(),
          synced: 0,
          uuid: crypto.randomUUID()
        } as any);
        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 handleUpdateItem = async () => {
    if (!selectedItem) return;
    try {
      const updated = { ...selectedItem, ...editedItem };
      if (updated.part_number && updated.part_number.trim().length === 0) {
        throw new Error("Part number cannot be empty");
      }
      if (updated.part_number) updated.part_number = updated.part_number.toUpperCase();

      await db.items.update(selectedItem.id!, updated);
      if (navigator.onLine) {
        await inventoryApi.updateItem(selectedItem.id!, updated);
      }
      
      toast.success("Item updated successfully");
      setIsEditing(false);
      setSelectedItem(updated as Item);
      await loadData();
    } catch (err: any) {
      console.error(err);
      toast.error("Failed to update item");
    }
  };

  const handleUpdateCategory = async () => {
    if (!editingCategory) return;
    try {
      await inventoryApi.updateCategory(editingCategory.id, {
        name: catEditedName,
        description: catEditedDesc
      });
      toast.success("Category updated");
      setEditingCategory(null);
      await loadData();
    } catch (err: any) {
      toast.error("Update failed");
    }
  };

  const onOCRMatch = useCallback(async (text: string) => {
    const cleanText = text.toUpperCase().replace(/[^A-Z0-9\s/+-]/g, ' ');
    const tokens = cleanText.split(/[\s\n,]+/).filter(t => t.length >= 3);
    
    if (fieldScanning?.active && fieldScanning.field === 'box_label') {
      const label = tokens[0] || cleanText;
      setEditedItem(prev => ({ ...prev, box_label: label }));
      setFieldScanning(null);
      setShowScanner(false);
      toast.success(`Captured: ${label}`);
      return;
    }
  }, [fieldScanning]);

  const onScanSuccess = useCallback((barcode: string) => {
    const item = inventory.find(i => i.barcode === barcode);
    if (item) {
      setSelectedItem(item);
      setShowScanner(false);
    } else {
      toast.error(`Item with barcode ${barcode} not found in catalog`);
    }
  }, [inventory]);

  const handleSearchItemSelect = (item: Item) => {
    setSelectedSearchItem(item);
    setShowQuantityModal(true);
  };

  const handleQuantityModalClose = () => {
    setShowQuantityModal(false);
    setSelectedSearchItem(null);
  };

  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-4 md:p-8 max-w-7xl mx-auto space-y-4">
      <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 className="flex items-center gap-4 mb-8">
        <div className="p-4 bg-primary/10 text-primary border border-primary/20">
          <Package size={28} className="md:w-8 md:h-8" />
        </div>
         <div>
           <h1 className="text-2xl md:text-3xl font-normal tracking-tight text-white leading-tight">Inventory Catalog</h1>
           <p className="text-xs md:text-sm text-secondary font-normal mt-1">Enterprise Stock Overview</p>
         </div>
        <button
          onClick={() => setShowSearchModal(true)}
          className="ml-auto p-3 bg-surface-container border border-border text-secondary hover:text-primary transition-all active:scale-95"
          title="Search Inventory"
        >
          <Search size={20} />
        </button>
        <button
          onClick={() => setShowBoxManager(true)}
          className="p-3 bg-surface-container border border-border text-secondary hover:text-primary transition-all active:scale-95"
          title="Manage Boxes"
        >
          <Layout size={20} />
        </button>
      </header>

      <div className="w-full space-y-4">
        <section className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard
            label="Categories"
            value={stats?.total_categories || categories.length}
            icon={Layers}
          />
          <StatCard
            label="Item Types"
            value={stats?.total_items || inventory.length}
            icon={Package}
          />
          <StatCard
            label="Total Boxes"
            value={existingBoxes.length}
            icon={Box}
          />
        </section>

        <FilterBar
          searchQuery={searchQuery}
          onChange={setSearchQuery}
        />

        <InventoryTable
          items={inventory}
          categories={filteredCategories}
          expandedCategory={expandedCategory}
          onExpandCategory={setExpandedCategory}
          onItemClick={setSelectedItem}
          onEditCategory={(cat) => {
            const categoryObj = categoriesList.find(c => c.name === cat);
            if (categoryObj) {
              setEditingCategory(categoryObj);
              setCatEditedName(categoryObj.name);
              setCatEditedDesc(categoryObj.description || '');
            }
          }}
          categoriesList={categoriesList}
          backendUrl={backendUrl}
        />
      </div>

      {selectedItem && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4 bg-background/90 animate-in fade-in duration-300">
          <div className="w-full max-w-lg level-2 p-5 sm:p-8 overflow-hidden animate-in slide-in-from-bottom-10 duration-300">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-xl font-normal tracking-tight flex items-center gap-2 text-white">
                   {isEditing ? "Edit Item" : selectedItem.name}
                   {!isEditing && (
                     <span className="text-xs bg-black text-secondary px-3 py-1 border border-border font-normal">
                       In Stock: {selectedItem.quantity}
                     </span>
                   )}
                </h3>
                <div className="flex gap-2">
                  {!isEditing && (
                    <button 
                      onClick={() => {
                        setEditedItem(selectedItem);
                        setIsEditing(true);
                      }} 
                      className="p-2 bg-surface-bright hover:text-primary transition-colors border border-border"
                    >
                      <Edit2 size={20} />
                    </button>
                  )}
                  <button 
                    onClick={() => {
                      setSelectedItem(null);
                      setIsEditing(false);
                      setAdjustQty(1);
                    }} 
                    className="p-2 bg-surface-bright hover:text-white transition-colors border border-border"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              {isEditing ? (
                <div className="max-h-[60vh] overflow-y-auto pr-2 space-y-3 mb-6 custom-scrollbar">
                   <div>
                    <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Item Name</label>
                    <input 
                      type="text" 
                      value={editedItem.name || ''} 
                      onChange={e => setEditedItem({...editedItem, name: e.target.value})}
                      className="input-field w-full"
                    />
                  </div>
                   <div>
                    <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Part Number</label>
                    <input
                      type="text"
                      value={editedItem.part_number || ''}
                      onChange={e => setEditedItem({...editedItem, part_number: e.target.value})}
                      className="input-field w-full"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                     <div>
                      <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Category</label>
                      <input 
                        type="text"
                        list="existing-categories"
                        value={editedItem.category || ''} 
                        onChange={e => setEditedItem({ ...editedItem, category: e.target.value })}
                        className="input-field w-full"
                        placeholder="e.g. Storage"
                      />
                    </div>
                     <div>
                      <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Item Type</label>
                      <input 
                        type="text" 
                        list="existing-types"
                        value={editedItem.type || ''} 
                        onChange={e => setEditedItem({...editedItem, type: e.target.value})}
                        className="input-field w-full"
                      />
                    </div>
                  </div>
                   <div>
                    <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Specs / Comments</label>
                    <textarea 
                      value={editedItem.specs || ''} 
                      onChange={e => setEditedItem({...editedItem, specs: e.target.value})}
                      className="input-field w-full h-24 resize-none"
                    />
                  </div>
                </div>
              ) : (
                <>
                  <div className="flex p-1 bg-black border border-border mb-6">
                    {[
                      { 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-rose-500' }
                    ].map((t) => (
                      <button
                        key={t.id}
                        onClick={() => setAdjustType(t.id as any)}
                        className={cn(
                          "flex-1 flex flex-col items-center py-4 transition-all",
                          adjustType === t.id ? "bg-surface-bright border border-border" : "text-secondary"
                        )}
                      >
                         <t.icon size={20} className={adjustType === t.id ? t.color : ""} />
                         <span className="text-xs font-normal mt-1.5">{t.label}</span>
                       </button>
                    ))}
                  </div>

                  <div className="flex flex-col items-center gap-4 mb-6">
                    <div className="flex items-center gap-6">
                      <button 
                        onClick={() => setAdjustQty(Math.max(1, adjustQty - 1))}
                        className="w-12 h-12 border border-border flex items-center justify-center bg-surface-bright hover:text-white"
                      >
                        <Minus size={24} />
                      </button>
                      <span className="text-5xl font-normal tabular-nums text-white">{adjustQty}</span>
                      <button 
                        onClick={() => setAdjustQty(adjustQty + 1)}
                        className="w-12 h-12 border border-border flex items-center justify-center bg-surface-bright hover:text-white"
                      >
                        <Plus size={24} />
                      </button>
                    </div>
                  </div>
                </>
              )}

              <button 
                onClick={isEditing ? handleUpdateItem : handleAdjustStock}
                className="btn-primary w-full py-4 text-lg"
              >
                {isEditing ? "Apply Changes" : (
                  adjustType === 'ADD' ? `Add ${adjustQty} To Stock` : 
                  adjustType === 'REMOVE' ? `Subtract ${adjustQty} From Stock` : 
                  `Discard ${adjustQty} Items`
                )}
              </button>
          </div>
        </div>
      )}

      {editingCategory && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/95 animate-in fade-in duration-300">
          <div className="level-2 p-6 max-w-sm w-full space-y-4 animate-in zoom-in-95 duration-200">
            <div className="flex justify-between items-center border-b border-border pb-2">
               <h2 className="text-xl font-normal text-white">Edit Category</h2>
               <button onClick={() => setEditingCategory(null)} className="p-2 bg-surface-bright hover:text-white text-secondary transition-colors border border-border">
                 <X size={20} />
               </button>
            </div>
            
            <div className="space-y-3">
               <div>
                <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Name</label>
                <input 
                  type="text" 
                  value={catEditedName}
                  onChange={e => setCatEditedName(e.target.value)}
                  className="input-field w-full"
                />
              </div>
               <div>
                <label className="text-xs font-normal text-secondary ml-1 tracking-tight">Description</label>
                <textarea 
                  value={catEditedDesc}
                  onChange={e => setCatEditedDesc(e.target.value)}
                  className="input-field w-full h-24 resize-none"
                />
              </div>
            </div>

            <button 
              onClick={handleUpdateCategory}
              className="btn-primary w-full py-3"
            >
              Update Protocol
            </button>
          </div>
        </div>
      )}

      {showScanner && (
        <Scanner 
          onScanSuccess={onScanSuccess} 
          onOCRMatch={onOCRMatch} 
        />
      )}
      </div>

      {showBoxManager && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/95 animate-in fade-in duration-300">
          <div className="w-full max-w-2xl level-2 overflow-hidden flex flex-col max-h-[90vh]">
            <div className="p-6 bg-surface-container/70 border-b border-border space-y-4">
               <div className="flex justify-between items-center">
                  <div>
                    <h3 className="text-2xl font-normal tracking-tight flex items-center gap-3 text-white">
                      <Package className="text-primary" size={28} />
                      Box Inventory
                    </h3>
                    <p className="text-xs text-secondary font-normal mt-1">Manage physical box labels & printing</p>
                  </div>
                  <button onClick={() => { setShowBoxManager(false); setBoxSearchQuery(''); }} className="p-3 bg-surface-bright border border-border text-secondary hover:text-white transition-colors">
                    <X size={24} />
                  </button>
               </div>

               <div className="relative">
                 <input 
                   type="text"
                   placeholder="Search Box Protocols..."
                   value={boxSearchQuery}
                   onChange={(e) => setBoxSearchQuery(e.target.value)}
                   className="input-field w-full pl-11"
                 />
                 <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-muted" size={18} />
               </div>
            </div>

            <div className="flex-1 overflow-y-auto p-6 space-y-3 custom-scrollbar">
               {getFilteredBoxes(existingBoxes).length === 0 ? (
                 <div className="py-20 text-center space-y-3 opacity-30">
                    <Package size={48} className="mx-auto text-secondary" />
                    <p className="text-secondary">No matching Box ID found</p>
                 </div>
               ) : (
                 <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    {getFilteredBoxes(existingBoxes).map(box => {
                        const itemCount = inventory.filter(i => i.box_label === box).length;
                        return (
                          <div key={box} className="bg-black/50 border border-border p-4 flex flex-col gap-3 group hover:border-primary/40 transition-all">
                             <div className="flex-1 min-w-0">
                                <h4 className="text-lg font-normal text-white truncate">{box}</h4>
                                <p className="text-xs text-secondary font-normal mt-0.5">{itemCount} Unique Records</p>
                             </div>
                             <div className="flex gap-2">
                                 <button 
                                   onClick={() => setSelectedBoxLabel(box)}
                                   className="btn-primary flex-1 text-xs py-2"
                                 >
                                   <Printer size={14} /> Print
                                 </button>
                                 <button 
                                   onClick={() => { setSearchQuery(box); setShowBoxManager(false); setBoxSearchQuery(''); }}
                                   className="btn-secondary flex-1 text-xs py-2"
                                 >
                                   View
                                 </button>
                             </div>
                          </div>
                        );
                      })}
                 </div>
               )}
            </div>
            
            <div className="p-4 bg-black border-t border-border flex items-center justify-center gap-2">
                <div className="w-1 h-1 bg-primary animate-pulse" />
                <p className="text-[10px] text-muted font-normal font-mono">TFM aInventory • Command Center • Box Protocols</p>
             </div>
          </div>
        </div>
      )}

      {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-4">

              <div id="print-label-area" className="w-full bg-white p-6 shadow-none flex flex-col items-center gap-4 border-none">
                 <h2 className="text-2xl font-normal text-black tracking-tighter text-center">
                   {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-normal 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="btn-primary w-full py-5 text-lg"
                 >
                   <Printer size={20} /> Deploy Print Job
                 </button>
                 
                 <button 
                   onClick={() => setSelectedBoxLabel(null)}
                   className="text-secondary hover:text-white transition-colors py-2 text-center text-xs"
                 >
                   Abort Label Preview
                 </button>
              </div>

              <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;
                  }
                  .no-print { display: none !important; }
                }
              `}} />
           </div>
        </div>
      )}

      <SearchModal
        isOpen={showSearchModal}
        onClose={() => setShowSearchModal(false)}
        onSelectItem={handleSearchItemSelect}
      />

      <QuantityAdjustmentModal
        item={selectedSearchItem}
        isOpen={showQuantityModal}
        onClose={handleQuantityModalClose}
      />
    </PageShell>
  );
}
