/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect } from 'react';
import {
  Layers,
  AlertTriangle,
  CheckCircle,
  HelpCircle,
  ArrowUpRight,
  TrendingUp,
  Sliders,
  DollarSign,
  PackageCheck,
  PlusSquare,
  ArrowRightLeft,
  XCircle,
  FolderSync,
  UploadCloud,
  Download,
  X,
} from 'lucide-react';
import { InventoryItem } from '../types';
import {
  useFiestaStockStatement,
  useFiestaTenantLocations,
} from '../services/fiestaQueries';
import { FIESTA_TENANT_ID, FIESTA_PRIMARY_LOCATION_ID, num as fnum, str as fstr } from '../services/fiestaApi';
import { stockRowToProduct, stockRowToInventory } from '../services/fiestaMappers';
import AwaitingApi from './AwaitingApi';

interface OperationsViewProps {
  searchQuery: string;
  isCoimbatoreView: boolean;
}

export default function OperationsView({ searchQuery, isCoimbatoreView }: OperationsViewProps) {
  // Sub-tabs state
  const [activeSubTab, setActiveSubTab] = useState<'inventory' | 'catalogue' | 'import'>('inventory');

  // ── Live operations data (Fiesta) ─────────────────────────────────────────
  const locationsQ = useFiestaTenantLocations(FIESTA_TENANT_ID);
  const primaryLocation =
    (locationsQ.data ?? []).find((l) => Number(l.locationid) === FIESTA_PRIMARY_LOCATION_ID) ||
    (locationsQ.data ?? [])[0];
  const locationId = primaryLocation ? Number(primaryLocation.locationid) : FIESTA_PRIMARY_LOCATION_ID;
  const locationName = fstr(primaryLocation?.locationname) || 'Primary Outlet';

  const stockQ = useFiestaStockStatement({
    tenantid: FIESTA_TENANT_ID,
    locationid: locationId,
    keyword: '',
    pageno: 1,
    pagesize: 100,
  });
  // Total inventory value = Σ closing × unit cost across the live stock statement.
  const inventoryValue = (stockQ.data ?? []).reduce(
    (sum, r) => sum + fnum(r.closing) * fnum(r.productcost),
    0,
  );

  // Dynamic state arrays for interaction (seeded from live data once it loads).
  const [inventoryList, setInventoryList] = useState<InventoryItem[]>([]);
  const [productList, setProductList] = useState<ReturnType<typeof stockRowToProduct>[]>([]);

  useEffect(() => {
    if (stockQ.data) {
      setProductList(stockQ.data.map(stockRowToProduct));
      setInventoryList(stockQ.data.map((r) => stockRowToInventory(r, locationName)));
    }
  }, [stockQ.data, locationName]);

  // Modal open states
  const [showAddSkuModal, setShowAddSkuModal] = useState(false);
  const [showTransferModal, setShowTransferModal] = useState(false);

  // Form states
  const [newSku, setNewSku] = useState({
    sku: '',
    name: '',
    warehouse: '',
    stockLevel: 0,
    maxCapacity: 1000,
    status: 'Optimal' as 'Optimal' | 'Low Stock' | 'Critical',
    region: 'CBE-NORTH' as 'CBE-NORTH' | 'CBE-SOUTH' | 'CBE-EAST' | 'CBE-WEST' | 'TIRUPPUR'
  });

  const [transferData, setTransferData] = useState({
    sku: '',
    origin: '',
    destination: '',
    quantity: 100
  });

  // Filter lists based on global Search query
  const filteredInventory = inventoryList.filter(item =>
    item.sku.toLowerCase().includes(searchQuery.toLowerCase()) ||
    item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    item.warehouse.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const filteredCatalogue = productList.filter(prod =>
    prod.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    prod.sku.toLowerCase().includes(searchQuery.toLowerCase()) ||
    prod.category.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Form submit handles
  const handleAddSku = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newSku.sku || !newSku.name || !newSku.warehouse) {
      alert('Please fill out all metadata fields before committing.');
      return;
    }

    const itemToAdd: InventoryItem = {
      sku: newSku.sku,
      name: newSku.name,
      warehouse: newSku.warehouse,
      stockLevel: Number(newSku.stockLevel),
      maxCapacity: Number(newSku.maxCapacity),
      status: newSku.stockLevel < 20 ? 'Critical' : newSku.stockLevel < 100 ? 'Low Stock' : 'Optimal',
      region: newSku.region
    };

    setInventoryList([itemToAdd, ...inventoryList]);
    setShowAddSkuModal(false);
    
    // reset form
    setNewSku({
      sku: '',
      name: '',
      warehouse: '',
      stockLevel: 0,
      maxCapacity: 1000,
      status: 'Optimal',
      region: 'CBE-NORTH'
    });
  };

  const handleExecuteTransfer = (e: React.FormEvent) => {
    e.preventDefault();
    if (!transferData.sku || !transferData.origin || !transferData.destination) {
      alert('Kindly configure transfer coordinates and SKU.');
      return;
    }

    // Attempt to update origin stock levels
    setInventoryList(prev => 
      prev.map(item => {
        if (item.sku === transferData.sku) {
          const newLevel = Math.max(0, item.stockLevel - transferData.quantity);
          return {
            ...item,
            stockLevel: newLevel,
            status: newLevel < 20 ? 'Critical' : newLevel < 100 ? 'Low Stock' : 'Optimal'
          };
        }
        return item;
      })
    );

    alert(`Transfer of ${transferData.quantity} units committed successfully. Tracking ID: TRF-${Math.floor(Math.random() * 900000 + 100000)}`);
    setShowTransferModal(false);
  };

  const handleToggleProductExposure = (id: string) => {
    setProductList(prev => 
      prev.map(p => p.id === id ? { ...p, verified: !p.verified } : p)
    );
  };

  return (
    <div className="space-y-lg animate-in fade-in duration-500">
      
      {/* Tab Navigation header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-end border-b border-[#e2e8f0] pb-px gap-2">
        <div>
          <h1 className="font-sans font-bold text-2xl tracking-tight text-[#0f172a]">
            Operations Hub{isCoimbatoreView && ': Coimbatore'}
          </h1>
          <p className="text-zinc-500 font-sans text-xs mt-1">
            Global product assortment, inventory levels, warehouse tracking, and data sync tools.
          </p>
        </div>

        {/* Dynamic Nav Sub-Tabs */}
        <nav className="flex gap-lg">
          {(['inventory', 'catalogue', 'import'] as const).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveSubTab(tab)}
              className={`font-sans text-xs font-semibold uppercase tracking-wider pb-2 cursor-pointer transition-colors relative ${
                activeSubTab === tab
                  ? 'text-[#662582] font-bold'
                  : 'text-zinc-400 hover:text-zinc-600'
              }`}
            >
              {tab}
              {activeSubTab === tab && (
                <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#662582] animate-in slide-in-from-left-2 duration-100" />
              )}
            </button>
          ))}
        </nav>
      </div>

      {/* Dynamic Display Area based on tabs selection */}
      {activeSubTab === 'inventory' && (
        <div className="space-y-lg">
          {/* Top Key Operational Indicators Grid */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-gutter">
            <div className="bg-white border border-[#e2e8f0] p-md rounded-xl flex justify-between items-start shadow-sm">
              <div>
                <p className="text-[11px] font-sans font-bold text-zinc-500 uppercase tracking-widest">
                  Total Inventory Value
                </p>
                <h3 className="font-sans font-bold text-[#0f172a] text-xl mt-xs">
                  ₹{inventoryValue.toLocaleString('en-IN', { maximumFractionDigits: 0 })}
                </h3>
                <p className="text-[11px] text-emerald-600 font-semibold mt-sm flex items-center gap-1.5">
                  <TrendingUp size={12} />
                  {productList.length} SKUs · {locationName}
                </p>
              </div>
              <div className="p-2.5 rounded-lg bg-purple-50 text-[#662582]">
                <DollarSign size={18} />
              </div>
            </div>

            <div className="bg-white border border-[#e2e8f0] p-md rounded-xl flex justify-between items-start shadow-sm">
              <div>
                <p className="text-[11px] font-sans font-bold text-zinc-500 uppercase tracking-widest">
                  Low Stock Alerts
                </p>
                <h3 className="font-sans font-bold text-rose-500 text-xl mt-xs">
                  {inventoryList.filter(item => item.status !== 'Optimal').length} SKUs
                </h3>
                <p className="text-[11px] text-zinc-400 mt-sm">Across local regional warehouses</p>
              </div>
              <div className="p-2.5 rounded-lg bg-rose-50 text-rose-500">
                <AlertTriangle size={18} />
              </div>
            </div>

            <div className="bg-white border border-[#e2e8f0] p-md rounded-xl flex justify-between items-start shadow-sm">
              <div>
                <p className="text-[11px] font-sans font-bold text-zinc-500 uppercase tracking-widest">
                  Fulfillment Health
                </p>
                <AwaitingApi label="Fulfillment health" api="[R1]" compact className="mt-xs" />
              </div>
              <div className="p-2.5 rounded-lg bg-emerald-50 text-emerald-600 animate-pulse">
                <PackageCheck size={18} />
              </div>
            </div>
          </div>

          {/* Sub Grid splits: Product state table (3 cols) and Action sidebar panels (1 col) */}
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-gutter">
            
            {/* Left table container */}
            <div className="lg:col-span-3 bg-white border border-[#e2e8f0] rounded-xl overflow-hidden flex flex-col justify-between shadow-sm">
              <div>
                <div className="p-md border-b border-[#e2e8f0] flex justify-between items-center bg-[#f8fafc]">
                  <h4 className="font-sans font-bold text-sm text-[#0f172a]">
                    Product Inventory Levels
                  </h4>
                  
                  <div className="flex gap-2 text-xs">
                    <span className="text-zinc-500 font-medium">Auto-synced</span>
                  </div>
                </div>

                <div className="overflow-x-auto">
                  <table className="w-full text-left font-sans text-xs">
                    <thead className="bg-[#f8fafc] border-b border-[#e2e8f0] text-zinc-500 text-[10px] uppercase tracking-wider font-semibold">
                      <tr>
                        <th className="p-md">Product SKU</th>
                        <th className="p-md">Warehouse</th>
                        <th className="p-md">Stock Level</th>
                        <th className="p-md">Status</th>
                        <th className="p-md text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[#f1f5f9]">
                      {filteredInventory.length === 0 ? (
                        <tr>
                          <td colSpan={5} className="text-center py-10 text-zinc-400">
                            No matching items identified. Try another query or reload.
                          </td>
                        </tr>
                      ) : (
                        filteredInventory.map((item, idx) => {
                          const percentage = (item.stockLevel / item.maxCapacity) * 100;
                          return (
                            <tr key={idx} className="hover:bg-[#f2f4f6]/50 transition-colors">
                              <td className="p-md">
                                <p className="font-bold text-[#0f172a]">{item.sku}</p>
                                <p className="text-[10px] text-zinc-400 font-medium">{item.name}</p>
                              </td>
                              <td className="p-md text-zinc-600 font-medium">
                                <span className="bg-[#f2f4f6] px-1.5 py-0.5 rounded text-[10px] font-mono mr-1">
                                  {item.region}
                                </span>
                                {item.warehouse}
                              </td>
                              <td className="p-md">
                                <p className="font-mono font-bold text-zinc-700">{item.stockLevel.toLocaleString()} units</p>
                                <div className="w-24 bg-[#eceef0] h-1 mt-1 rounded-full overflow-hidden">
                                  <div 
                                    className={`h-full rounded-full ${
                                      item.status === 'Critical' ? 'bg-rose-500' : item.status === 'Low Stock' ? 'bg-amber-500' : 'bg-[#662582]'
                                    }`} 
                                    style={{ width: `${Math.min(percentage, 100)}%` }} 
                                  />
                                </div>
                              </td>
                              <td className="p-md">
                                <span className={`px-2 py-0.5 rounded-full text-[10px] uppercase font-bold tracking-tight inline-block ${
                                  item.status === 'Critical' 
                                    ? 'bg-rose-100 text-rose-750' 
                                    : item.status === 'Low Stock' 
                                    ? 'bg-amber-100 text-amber-750' 
                                    : 'bg-emerald-100 text-emerald-750'
                                }`}>
                                  {item.status}
                                </span>
                              </td>
                              <td className="p-md text-right">
                                <div className="flex justify-end gap-1">
                                  <button
                                    onClick={() => {
                                      setTransferData({
                                        sku: item.sku,
                                        origin: item.warehouse,
                                        destination: '',
                                        quantity: 50
                                      });
                                      setShowTransferModal(true);
                                    }}
                                    className="text-xs font-semibold text-[#662582] hover:underline cursor-pointer"
                                  >
                                    Transfer
                                  </button>
                                </div>
                              </td>
                            </tr>
                          );
                        })
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
              
              <div className="p-md border-t border-[#f1f5f9] bg-[#f8fafc] flex justify-between items-center text-[10px] text-zinc-500 font-medium font-sans">
                <span>Displaying 1-{filteredInventory.length} of {inventoryList.length} global items</span>
                <span>Active Ledger Nodes Online</span>
              </div>
            </div>

            {/* Right sidebar quick tasks */}
            <div className="space-y-gutter">
              {/* Forecast module visual details */}
              <div className="bg-[#0f172a] text-white p-6 rounded-xl relative overflow-hidden flex flex-col justify-between shadow-md h-48">
                <div>
                  <span className="text-[10px] tracking-wider font-bold opacity-60 uppercase">
                    Forecast Efficiency
                  </span>
                  <AwaitingApi
                    label="Forecast insights"
                    api="[R7]"
                    compact
                    className="mt-sm bg-white/5 border-white/15 text-zinc-300"
                  />
                </div>

                {/* Embedded SVG graphic visual */}
                <div className="absolute right-3 bottom-3 opacity-15">
                  <PackageCheck size={64} className="text-purple-300" />
                </div>
              </div>

              {/* Quick Actions buttons block */}
              <div className="bg-white border border-[#e2e8f0] rounded-xl p-md shadow-sm">
                <span className="text-[10px] font-sans font-bold text-zinc-400 uppercase tracking-widest block pb-xs mb-md border-b border-[#f1f5f9]">
                  Quick Actions Ledger
                </span>

                <div className="grid grid-cols-2 gap-sm">
                  <button
                    onClick={() => setShowAddSkuModal(true)}
                    className="bg-[#f8fafc] border border-[#e2e8f0] p-sm rounded-lg flex flex-col items-center gap-xs text-zinc-700 hover:bg-[#faf5ff] hover:text-[#662582] hover:border-[#662582] transition-all cursor-pointer group"
                  >
                    <PlusSquare size={16} className="text-zinc-400 group-hover:text-[#662582]" />
                    <span className="text-[10px] font-sans font-bold uppercase">Add SKU</span>
                  </button>

                  <button
                    onClick={() => {
                      setTransferData({ sku: 'PRO-9920-X1', origin: 'RS Puram Hub (CBE-01)', destination: '', quantity: 100 });
                      setShowTransferModal(true);
                    }}
                    className="bg-[#f8fafc] border border-[#e2e8f0] p-sm rounded-lg flex flex-col items-center gap-xs text-zinc-700 hover:bg-[#faf5ff] hover:text-[#662582] hover:border-[#662582] transition-all cursor-pointer group"
                  >
                    <ArrowRightLeft size={16} className="text-zinc-400 group-hover:text-[#662582]" />
                    <span className="text-[10px] font-sans font-bold uppercase">Transfer</span>
                  </button>

                  <button
                    onClick={() => {
                      const amount = prompt('Enter return item SKU code:');
                      if (amount) {
                        alert(`Returns logged successfully for target SKU code ${amount}. Waiting for physical hub clearance inspection.`);
                      }
                    }}
                    className="bg-[#f8fafc] border border-[#e2e8f0] p-sm rounded-lg flex flex-col items-center gap-xs text-zinc-700 hover:bg-[#faf5ff] hover:text-[#662582] hover:border-[#662582] transition-all cursor-pointer group"
                  >
                    <XCircle size={16} className="text-zinc-400 group-hover:text-[#662582]" />
                    <span className="text-[10px] font-sans font-bold uppercase">Returns</span>
                  </button>

                  <button
                    onClick={() => {
                      alert('Generating automated physical audit compliance report draft sheets... Download started background.');
                    }}
                    className="bg-[#f8fafc] border border-[#e2e8f0] p-sm rounded-lg flex flex-col items-center gap-xs text-zinc-700 hover:bg-[#faf5ff] hover:text-[#662582] hover:border-[#662582] transition-all cursor-pointer group"
                  >
                    <FolderSync size={16} className="text-zinc-400 group-hover:text-[#662582]" />
                    <span className="text-[10px] font-sans font-bold uppercase">Audit CSV</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeSubTab === 'catalogue' && (
        <div className="space-y-md animate-in slide-in-from-right-5">
          <div className="flex justify-between items-end bg-[#f8fafc] border border-[#e2e8f0] p-md rounded-xl shadow-sm">
            <div>
              <h3 className="font-sans font-bold text-sm text-[#0f172a]">
                Master Assortment Catalogue
              </h3>
              <p className="text-zinc-500 text-xs font-sans mt-0.5">
                Global inventory master list and exposure levels across {productList.length.toLocaleString('en-IN')} nodes.
              </p>
            </div>
            
            <button
              onClick={() => {
                const title = prompt('Enter product brand title:');
                const sku = prompt('Enter SKU catalogue code:');
                const category = prompt('Enter SKU Category:');
                if (title && sku && category) {
                  setProductList(prev => [
                    ...prev,
                    {
                      id: String(prev.length + 1),
                      name: title,
                      sku: sku,
                      unitsSold: 0,
                      revenue: 0,
                      stockStatus: 'Healthy',
                      trend: 'flat',
                      image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=150&q=80',
                      category: category,
                      exposure: '0/120 Stores',
                      verified: false
                    }
                  ]);
                  alert(`${title} added successfully to unreleased draft portfolio.`);
                }
              }}
              className="bg-[#662582] hover:bg-purple-800 active:bg-purple-900 text-white font-sans text-xs font-semibold px-4 py-2 rounded-lg cursor-pointer transition-colors shadow-sm"
            >
              Add Brand Product
            </button>
          </div>

          <div className="bg-white border border-[#e2e8f0] rounded-xl overflow-hidden shadow-sm">
            <table className="w-full text-left font-sans text-xs">
              <thead className="bg-[#f8fafc] border-b border-[#e2e8f0] text-zinc-500 text-[10px] uppercase font-bold tracking-wider">
                <tr>
                  <th className="p-md">Product Details</th>
                  <th className="p-md">Category segment</th>
                  <th className="p-md">Verification status</th>
                  <th className="p-md">Store exposure</th>
                  <th className="p-md text-right">Exposure toggle</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#f1f5f9]">
                {filteredCatalogue.map((prod) => (
                  <tr key={prod.id} className="hover:bg-[#f2f4f6]/50 transition-colors">
                    <td className="p-md flex items-center gap-md">
                      <div className="w-10 h-10 rounded-lg border border-[#e2e8f0] overflow-hidden shrink-0 bg-zinc-50">
                        <img 
                          src={prod.image} 
                          alt={prod.name} 
                          referrerPolicy="no-referrer"
                          className="w-full h-full object-cover" 
                        />
                      </div>
                      <div>
                        <p className="font-bold text-[#0f172a]">{prod.name}</p>
                        <p className="text-[10px] text-zinc-400 font-mono">SKU: {prod.sku}</p>
                      </div>
                    </td>
                    <td className="p-md text-zinc-600 font-medium">{prod.category}</td>
                    <td className="p-md">
                      {prod.verified ? (
                        <span className="flex items-center gap-1.5 text-emerald-600 font-semibold tracking-tight text-[11px]">
                          <span className="w-2 h-2 rounded-full bg-emerald-500"></span> Verified Portfolio
                        </span>
                      ) : (
                        <span className="flex items-center gap-1.5 text-zinc-400 font-medium tracking-tight text-[11px]">
                          <span className="w-2 h-2 rounded-full bg-zinc-300"></span> Under Inspection
                        </span>
                      )}
                    </td>
                    <td className="p-md text-zinc-500 font-medium">{prod.exposure}</td>
                    <td className="p-md text-right">
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={prod.verified}
                          onChange={() => handleToggleProductExposure(prod.id)}
                          className="sr-only peer"
                        />
                        <div className="w-9 h-5 bg-zinc-200 rounded-full peer peer-focus:ring-0 peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-zinc-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#662582]"></div>
                      </label>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeSubTab === 'import' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-gutter animate-in slide-in-from-right-5">
          {/* Upload panel zone */}
          <div
            onClick={() => {
              const fileRef = prompt('Enter CSV filename representation path:');
              if (fileRef) {
                alert('Uploaded successfully. Metadata schema verification committed.');
              }
            }}
            className="bg-white border-2 border-dashed border-zinc-300 rounded-xl p-xl flex flex-col items-center justify-center text-center cursor-pointer hover:bg-[#faf5ff]/30 hover:border-[#662582] transition-all duration-200"
          >
            <div className="h-14 w-14 bg-purple-50 text-[#662582] rounded-full flex items-center justify-center mb-md shadow-sm">
              <UploadCloud size={24} />
            </div>
            
            <h4 className="font-sans font-bold text-base text-[#0f172a]">
              Upload Inventory CSV
            </h4>
            
            <p className="text-zinc-500 text-xs mt-2 max-w-[20rem] leading-relaxed">
              Drag and drop your .csv, .xlsx or .xml sheets here to automatically update global stock balances or master portfolios schemas.
            </p>

            <div className="mt-lg flex gap-md">
              <button className="bg-[#0f172a] text-white text-xs font-semibold px-4 py-2 rounded-lg cursor-pointer hover:bg-zinc-800 transition-colors shadow-sm">
                Browse Files
              </button>
              <button 
                onClick={(e) => {
                  e.stopPropagation();
                  alert('Template documentation initiated.');
                }}
                className="bg-white border border-[#e2e8f0] text-zinc-600 text-xs px-4 py-2 rounded-lg cursor-pointer hover:bg-zinc-50 transition-colors"
              >
                Template CSV
              </button>
            </div>
          </div>

          {/* Validation indicators checker logs split */}
          <div className="bg-white border border-[#e2e8f0] p-md rounded-xl flex flex-col justify-between shadow-sm">
            <div>
              <span className="text-[10px] font-sans font-bold text-zinc-400 uppercase tracking-widest block pb-xs mb-md border-b border-[#f1f5f9]">
                Interactive Schema Validator
              </span>

              <AwaitingApi label="Import audit & validation" api="[R4]" />
            </div>
          </div>
        </div>
      )}

      {/* MODAL 1: ADD SKU MODAL */}
      {showAddSkuModal && (
        <div className="fixed inset-0 bg-[#0f172a]/40 backdrop-blur-xs z-[150] flex items-center justify-center p-md animate-in fade-in duration-150">
          <div className="bg-white border border-[#e2e8f0] rounded-xl w-full max-w-[28rem] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
            <div className="p-md border-b border-[#e2e8f0] bg-[#f8fafc] flex justify-between items-center">
              <h4 className="font-sans font-bold text-sm text-[#0f172a]">
                Add Item SKU to Balance Ledger
              </h4>
              <button 
                onClick={() => setShowAddSkuModal(false)}
                className="p-1.5 hover:bg-zinc-200 rounded-full text-zinc-400 cursor-pointer text-left"
              >
                <X size={16} />
              </button>
            </div>

            <form onSubmit={handleAddSku} className="p-md space-y-md text-xs">
              <div className="grid grid-cols-2 gap-sm">
                <div className="space-y-1">
                  <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">SKU Code (*)</label>
                  <input 
                    type="text" 
                    placeholder="e.g., SKU-1290-A"
                    value={newSku.sku}
                    onChange={(e) => setNewSku({ ...newSku, sku: e.target.value })}
                    className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                    required
                  />
                </div>
                
                <div className="space-y-1">
                  <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">Product Name</label>
                  <input 
                    type="text" 
                    placeholder="e.g., Thermal Printer"
                    value={newSku.name}
                    onChange={(e) => setNewSku({ ...newSku, name: e.target.value })}
                    className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1">
                <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">Target Warehouse</label>
                <input 
                  type="text" 
                  placeholder="e.g., Coimbatore main logistics CBE"
                  value={newSku.warehouse}
                  onChange={(e) => setNewSku({ ...newSku, warehouse: e.target.value })}
                  className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-sm">
                <div className="space-y-1">
                  <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">Initial Balance</label>
                  <input 
                    type="number" 
                    value={newSku.stockLevel}
                    onChange={(e) => setNewSku({ ...newSku, stockLevel: Number(e.target.value) })}
                    className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                    required
                  />
                </div>

                <div className="space-y-1">
                  <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">Warehouse Region</label>
                  <select
                    value={newSku.region}
                    onChange={(e) => setNewSku({ ...newSku, region: e.target.value as any })}
                    className="w-full border border-[#e2e8f0] rounded-lg p-2 bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                  >
                    <option value="CBE-NORTH">Coimbatore North (CBE-NORTH)</option>
                    <option value="CBE-SOUTH">Coimbatore South (CBE-SOUTH)</option>
                    <option value="CBE-EAST">Coimbatore East (CBE-EAST)</option>
                    <option value="CBE-WEST">Coimbatore West (CBE-WEST)</option>
                    <option value="TIRUPPUR">Tiruppur Regional Hub (TIRUPPUR)</option>
                  </select>
                </div>
              </div>

              <div className="pt-sm border-t border-[#f1f5f9] flex justify-end gap-sm">
                <button
                  type="button"
                  onClick={() => setShowAddSkuModal(false)}
                  className="px-4 py-2 border border-[#e2e8f0] rounded-lg font-semibold text-zinc-500 hover:bg-zinc-50 cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-[#662582] text-white rounded-lg font-semibold hover:bg-purple-800 cursor-pointer shadow-sm"
                >
                  Commit Ledger SKU
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL 2: TRANSFER STOCK MODAL */}
      {showTransferModal && (
        <div className="fixed inset-0 bg-[#0f172a]/40 backdrop-blur-xs z-[150] flex items-center justify-center p-md animate-in fade-in duration-150">
          <div className="bg-white border border-[#e2e8f0] rounded-xl w-full max-w-[24rem] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
            <div className="p-md border-b border-[#e2e8f0] bg-[#f8fafc] flex justify-between items-center">
              <h4 className="font-sans font-bold text-sm text-[#0f172a]">
                Request Node Stock Transfer
              </h4>
              <button 
                onClick={() => setShowTransferModal(false)}
                className="p-1 hover:bg-zinc-200 rounded-full text-zinc-400 cursor-pointer"
              >
                <X size={16} />
              </button>
            </div>

            <form onSubmit={handleExecuteTransfer} className="p-md space-y-md text-xs">
              <div className="space-y-1">
                <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">TRANSFERRING SKU</label>
                <input 
                  type="text" 
                  value={transferData.sku}
                  onChange={(e) => setTransferData({ ...transferData, sku: e.target.value })}
                  className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] font-mono focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                  required
                />
              </div>

              <div className="space-y-1">
                <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">ORIGIN WAREHOUSE</label>
                <input 
                  type="text" 
                  value={transferData.origin}
                  onChange={(e) => setTransferData({ ...transferData, origin: e.target.value })}
                  className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none text-zinc-800 font-medium focus:ring-1 focus:ring-[#662582]"
                  required
                />
              </div>

              <div className="space-y-1">
                <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">TARGET DESTINATION WAREHOUSE</label>
                <input 
                  type="text" 
                  placeholder="e.g., Coimbatore South CBE-03"
                  value={transferData.destination}
                  onChange={(e) => setTransferData({ ...transferData, destination: e.target.value })}
                  className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                  required
                />
              </div>

              <div className="space-y-1">
                <label className="font-bold text-zinc-500 uppercase tracking-widest block text-[9px]">TRANSFER QUANTITY</label>
                <input 
                  type="number" 
                  value={transferData.quantity}
                  onChange={(e) => setTransferData({ ...transferData, quantity: Number(e.target.value) })}
                  className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f1f5f9] focus:bg-white outline-none focus:ring-1 focus:ring-[#662582]"
                  required
                />
              </div>

              <div className="pt-sm border-t border-[#f1f5f9] flex justify-end gap-sm">
                <button
                  type="button"
                  onClick={() => setShowTransferModal(false)}
                  className="px-4 py-2 border border-[#e2e8f0] rounded-lg font-semibold text-zinc-500 hover:bg-zinc-50 cursor-pointer"
                >
                  Close
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-[#662582] text-white rounded-lg font-semibold hover:bg-purple-800 cursor-pointer shadow-sm"
                >
                  Approve Routing
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
