'use client';

/**
 * POS Page
 * Point of Sale interface for creating sales - Modern cashier-friendly design
 */

import { useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useMutation, useQuery } from '@tanstack/react-query';
import { salesAPI, productsAPI, discountsAPI } from '@/lib/api';
import { inventoryAPI } from '@/lib/api/inventory';
import { useAuth } from '@/contexts/AuthContext';
import ProductGrid from '@/components/features/pos/ProductGrid';
import Cart from '@/components/features/pos/Cart';
import CategorySidebar from '@/components/features/pos/CategorySidebar';
// CustomerSelect removed - walk-in customers only
import PaymentModal from '@/components/features/pos/PaymentModal';
import StockWarningModal from '@/components/features/pos/StockWarningModal';
import ManagerApprovalModal from '@/components/features/pos/ManagerApprovalModal';
import ManualMPesaConfirmModal from '@/components/features/pos/ManualMPesaConfirmModal';
import { Button, Input } from '@/components/ui';
import { formatCurrency } from '@/lib/utils/format';
import { ShoppingCart, RotateCcw, CreditCard, Scan, Tag, X } from 'lucide-react';
import toast from 'react-hot-toast';

export default function POSPage() {
  const router = useRouter();
  const { user, hasAnyRole } = useAuth();
  const isManagerOrAdmin = hasAnyRole(['manager', 'system_admin']);
  
  const [selectedCategoryId, setSelectedCategoryId] = useState(null);
  // selectedCustomer removed - walk-in customers only
  const [cartItems, setCartItems] = useState([]);
  const [currentSaleId, setCurrentSaleId] = useState(null);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [showStockWarning, setShowStockWarning] = useState(false);
  const [showManagerApproval, setShowManagerApproval] = useState(false);
  const [showManualMPesaConfirm, setShowManualMPesaConfirm] = useState(false);
  const [pendingProduct, setPendingProduct] = useState(null);
  const [stockWarnings, setStockWarnings] = useState([]);
  const [pendingApproval, setPendingApproval] = useState({ type: null, items: [], reason: '' });
  const [pendingMPesaPaymentId, setPendingMPesaPaymentId] = useState(null);
  const [discountCode, setDiscountCode] = useState('');
  const [appliedDiscount, setAppliedDiscount] = useState(null);
  const [discountError, setDiscountError] = useState('');
  const [discountAmount, setDiscountAmount] = useState(0);
  const [itemDiscounts, setItemDiscounts] = useState({}); // Map of item_id -> available discounts array
  const [cartDiscounts, setCartDiscounts] = useState([]); // Array of available cart-level discounts
  const [barcodeInput, setBarcodeInput] = useState('');
  const [isScanning, setIsScanning] = useState(false);
  const [isRemovalMode, setIsRemovalMode] = useState(false); // Track if we're in scan-to-remove mode
  const [showCart, setShowCart] = useState(false);
  const [showCategories, setShowCategories] = useState(false); // Collapsed by default
  const [rightSidebarCollapsed, setRightSidebarCollapsed] = useState(true); // Cart collapsed by default
  const barcodeInputRef = useRef(null);
  // Tax calculations removed - tax functionality removed from system

  // Fetch all active cart-level discounts (discounts with codes)
  const { data: discountsData } = useQuery({
    queryKey: ['cart-discounts'],
    queryFn: async () => {
      try {
        const response = await discountsAPI.list({ active: true, limit: 100 });
        const discounts = response?.data?.discounts || response?.discounts || [];
        // Filter for discounts that have codes (cart-level discounts)
        // Cart-level discounts should have codes, per-product discounts may not
        const cartLevelDiscounts = discounts.filter(d => d.code && d.code.trim() !== '');
        setCartDiscounts(cartLevelDiscounts);
        return cartLevelDiscounts;
      } catch (error) {
        console.error('Error fetching cart discounts:', error);
        setCartDiscounts([]);
        return [];
      }
    },
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  });

  // Calculate item total with discount
  const calculateItemTotal = (item) => {
    const baseTotal = item.quantity * item.unit_price;
    if (!item.discount_id || !item.discount) {
      return baseTotal;
    }
    
    const discount = item.discount;
    let discountAmount = 0;
    
    if (discount.discount_type === 'PERCENTAGE') {
      discountAmount = (baseTotal * discount.discount_value) / 100;
      if (discount.max_discount_amount) {
        discountAmount = Math.min(discountAmount, discount.max_discount_amount);
      }
    } else if (discount.discount_type === 'FIXED_AMOUNT') {
      discountAmount = Math.min(discount.discount_value, baseTotal);
    }
    
    return baseTotal - discountAmount;
  };

  // Calculate totals (tax removed, includes per-item discounts)
  const subtotal = cartItems.reduce(
    (sum, item) => sum + item.quantity * item.unit_price,
    0
  );
  const itemDiscountsTotal = cartItems.reduce(
    (sum, item) => {
      const baseTotal = item.quantity * item.unit_price;
      if (!item.discount_id || !item.discount) {
        return sum;
      }
      
      const discount = item.discount;
      let discountAmount = 0;
      
      if (discount.discount_type === 'PERCENTAGE') {
        discountAmount = (baseTotal * discount.discount_value) / 100;
        if (discount.max_discount_amount) {
          discountAmount = Math.min(discountAmount, discount.max_discount_amount);
        }
      } else if (discount.discount_type === 'FIXED_AMOUNT') {
        discountAmount = Math.min(discount.discount_value, baseTotal);
      }
      
      return sum + discountAmount;
    },
    0
  );

  // Cart-level discount amount from applied discount code
  const discount = discountAmount;

  // Total discount (per-item + cart-level)
  const totalDiscountAmount = itemDiscountsTotal + discount;

  const tax = 0; // Tax removed - always 0
  const total = subtotal - totalDiscountAmount; // Total includes per-item and cart-level discounts

  // Create sale mutation
  const createSaleMutation = useMutation({
    mutationFn: (saleData) => salesAPI.create(saleData),
    onSuccess: (response) => {
      if (response.success) {
        setCurrentSaleId(response.data.id || response.data.sale?.id);
        setShowPaymentModal(true);
        toast.success('Sale created successfully');
      }
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to create sale');
    },
  });

  // Handle product selection with stock checking
  const handleProductSelect = async (product) => {
    // Only find existing manual items (not scanned items) for the same product
    // This ensures scanned and manual items stay separate
    const existingItem = cartItems.find(
      (item) => item.product_id === product.id && 
                !item.variant_id &&
                item.added_via === 'manual' // Only merge with manual items
    );

    const requestedQuantity = existingItem ? existingItem.quantity + 1 : 1;

    // Check if product tracks inventory
    if (product.track_inventory) {
      // Try to use inventory from product object first (if included in API response)
      let availableQty = null;
      
      if (product.inventory && product.inventory.available_qty !== null && product.inventory.available_qty !== undefined) {
        // Use inventory from product object (no API call needed)
        availableQty = parseFloat(product.inventory.available_qty || 0);
      } else {
        // Fallback: Make API call if inventory not included
        try {
          const availabilityResponse = await productsAPI.getAvailability(product.id);
          const availability = availabilityResponse.data || availabilityResponse;
          availableQty = parseFloat(availability.available_qty || 0);
        } catch (error) {
          console.error('Stock check error:', error);
          // If stock check fails, proceed anyway (might be network issue)
          availableQty = null;
        }
      }

      // If we have inventory data and insufficient stock, show warning
      if (availableQty !== null && availableQty < requestedQuantity) {
        const warnings = [{
          product_id: product.id,
          product_name: product.name,
          requested: requestedQuantity,
          available: availableQty,
          shortfall: Math.max(0, requestedQuantity - availableQty),
          status: availableQty > 0 ? 'PARTIAL' : 'OUT_OF_STOCK',
        }];
        setStockWarnings(warnings);
        setPendingProduct({ ...product, quantity: requestedQuantity, existingItem });
        setShowStockWarning(true);
        return;
      }
    }

    // Stock is sufficient (or not tracked), add to cart
    if (existingItem) {
      handleUpdateQuantity(existingItem, requestedQuantity);
    } else {
      // Use price from product object (from API with include=prices)
      const unitPrice = product.price?.amount || product.selling_price || 0;
      const newItemId = `temp-${Date.now()}-${Math.random()}`;
      const newItem = {
        id: newItemId,
        product_id: product.id,
        product_name: product.name,
        unit_price: unitPrice,
        quantity: 1,
        added_via: 'manual', // Track that this was added manually
      };
      setCartItems([...cartItems, newItem]);
      
      // Fetch available discounts for this product
      fetchItemDiscounts(product.id, newItemId);
      
      toast.success(`${product.name} added to cart`, { duration: 1500 });
    }
  };

  // Fetch available discounts for a product
  const fetchItemDiscounts = async (productId, itemId) => {
    try {
      const response = await discountsAPI.getForProduct(productId);
      const discounts = response?.data?.discounts || response?.discounts || [];
      setItemDiscounts((prev) => ({
        ...prev,
        [itemId]: discounts,
      }));
    } catch (error) {
      // Log more detailed error information
      console.error('Error fetching discounts for product:', {
        productId,
        itemId,
        error: error?.response?.data || error?.message || error,
        status: error?.response?.status,
      });
      // Set empty array to avoid undefined errors in UI
      setItemDiscounts((prev) => ({
        ...prev,
        [itemId]: [],
      }));
      // Don't show error toast, just silently fail - discounts are optional
    }
  };

  // Handle item discount change
  const handleItemDiscountChange = (item, discountId) => {
    const discounts = itemDiscounts[item.id] || [];
    const selectedDiscount = discounts.find((d) => d.id === discountId);
    
    setCartItems((prevItems) =>
      prevItems.map((i) =>
        i.id === item.id
          ? {
              ...i,
              discount_id: discountId || null,
              discount: selectedDiscount || null,
            }
          : i
      )
    );
  };

  // Handle proceed with stock warning (from adding item)
  const handleProceedWithStockWarning = () => {
    if (pendingProduct) {
      // Adding item to cart
      const { existingItem, quantity, ...product } = pendingProduct;

      // existingItem should already be a manual item (from handleProductSelect logic)
      if (existingItem && existingItem.added_via === 'manual') {
        handleUpdateQuantity(existingItem, quantity);
      } else {
        // Use price from product object (from API with include=prices)
        const unitPrice = product.price?.amount || product.selling_price || 0;
        const newItemId = `temp-${Date.now()}-${Math.random()}`;
        const newItem = {
          id: newItemId,
          product_id: product.id,
          product_name: product.name,
          unit_price: unitPrice,
          quantity: 1,
          added_via: 'manual', // Track that this was added manually
          stockWarning: stockWarnings.find(w => w.product_id === product.id),
        };
        setCartItems([...cartItems, newItem]);
        
        // Fetch available discounts for this product
        fetchItemDiscounts(product.id, newItemId);
      }

      setShowStockWarning(false);
      setPendingProduct(null);
      setStockWarnings([]);
      toast.success(`${product.name} added to cart`, { duration: 1500 });
    } else {
      // Proceeding with checkout despite stock warnings
      setShowStockWarning(false);
      setStockWarnings([]);
      
    // Proceed with sale creation
    const saleData = {
      sale_type: 'POS',
      customer_id: null, // Walk-in customers only - customer registration removed
      // Persist the same monetary values used in POS UI so backend and payments stay in sync
      subtotal,
      discount_amount: totalDiscountAmount,
      total,
      items: cartItems.map((item) => ({
        product_id: item.product_id,
        variant_id: item.variant_id || null,
        quantity: item.quantity,
        unit_price: item.unit_price,
        discount_id: item.discount_id || null, // Include per-item discount (used client-side)
      })),
      ...(appliedDiscount && { discount_code: discountCode.trim().toUpperCase() }),
    };

    createSaleMutation.mutate(saleData);
    }
  };

  // Handle quantity update
  const handleUpdateQuantity = (item, newQuantity) => {
    if (newQuantity <= 0) {
      handleRemoveItem(item);
      return;
    }

    // For scanned items, quantity should match scanned_uids length
    // Prevent manual quantity decrease for scanned items
    if (item.added_via === 'scan' && item.scanned_uids && newQuantity < item.scanned_uids.length) {
      toast.error('Cannot reduce quantity below scanned items. Use delete button to remove specific UIDs.', { duration: 3000 });
      return;
    }

    const updatedItem = { ...item, quantity: newQuantity };

    setCartItems(
      cartItems.map((cartItem) =>
        cartItem.id === item.id ? updatedItem : cartItem
      )
    );
  };

  // Handle remove item
  const handleRemoveItem = (item) => {
    setCartItems(cartItems.filter((cartItem) => cartItem.id !== item.id));
    toast.success('Item removed', { duration: 1500 });
  };

  // Check stock mutation for bulk checking
  const checkStockMutation = useMutation({
    mutationFn: (items) => salesAPI.checkStock(items),
  });

  // Check for RM products requiring approval
  const checkRMProducts = async (items) => {
    try {
      // Fetch product details to check sell_on_pos flag
      const productIds = [...new Set(items.map(item => item.product_id))];
      const productChecks = await Promise.all(
        productIds.map(async (productId) => {
          try {
            const productResponse = await productsAPI.getById(productId);
            const product = productResponse.data || productResponse;
            return { productId, sell_on_pos: product.sell_on_pos, name: product.name };
          } catch (error) {
            console.error(`Error fetching product ${productId}:`, error);
            return { productId, sell_on_pos: true, name: 'Unknown' }; // Assume sellable if can't fetch
          }
        })
      );

      // Find RM products that need approval (sell_on_pos = false and user is not manager/admin)
      const rmProductsNeedingApproval = items
        .filter(item => {
          const productInfo = productChecks.find(p => p.productId === item.product_id);
          return productInfo && !productInfo.sell_on_pos && !isManagerOrAdmin;
        })
        .map(item => {
          const productInfo = productChecks.find(p => p.productId === item.product_id);
          return {
            ...item,
            product_name: productInfo?.name || 'Unknown Product',
          };
        });

      return rmProductsNeedingApproval;
    } catch (error) {
      console.error('Error checking RM products:', error);
      return [];
    }
  };

  // Proceed with sale creation (with optional approval data)
  const proceedWithSaleCreation = (approvalData = null) => {
    const saleData = {
      sale_type: 'POS',
      customer_id: null, // Walk-in customers only - customer registration removed
      // Persist the same monetary values used in POS UI so backend and payments stay in sync
      subtotal,
      discount_amount: totalDiscountAmount,
      total,
      items: cartItems.map((item) => ({
        product_id: item.product_id,
        variant_id: item.variant_id || null,
        quantity: item.quantity,
        unit_price: item.unit_price,
        // Pass scanned UIDs for UID-based inventory tracking
        ...(item.added_via === 'scan' && item.scanned_uids && {
          scanned_uids: item.scanned_uids,
        }),
      })),
      ...(approvalData?.manager_approval_id && {
        manager_approval_id: approvalData.manager_approval_id,
      }),
      ...(approvalData?.stock_override && {
        stock_override: true,
        stock_override_reason: approvalData.stock_override_reason,
      }),
    };

    createSaleMutation.mutate(saleData);
  };

  // Handle manager approval
  const handleManagerApproval = (reason = null) => {
    const approvalData = {
      ...(pendingApproval.type === 'RM_SALE' && {
        manager_approval_id: user?.id, // Current user (manager) approves
      }),
      ...(pendingApproval.type === 'STOCK_OVERRIDE' && {
        stock_override: true,
        stock_override_reason: reason || 'Manager approved stock override',
      }),
    };

    setShowManagerApproval(false);
    setPendingApproval({ type: null, items: [], reason: '' });
    proceedWithSaleCreation(approvalData);
  };

  // Handle discount code application
  const handleApplyDiscount = async () => {
    if (!discountCode.trim()) {
      setDiscountError('');
      setAppliedDiscount(null);
      setDiscountAmount(0);
      return; // No discount selected, just clear any existing discount
    }

    if (cartItems.length === 0) {
      setDiscountError('Cart is empty');
      return;
    }

    setDiscountError('');

    try {
      // Find discount from cartDiscounts or fetch by code
      let discount = cartDiscounts.find(d => (d.code || d.id.toString()) === discountCode);
      
      if (!discount) {
        // Try to fetch by code if not found in local list
        const discountResponse = await discountsAPI.getByCode(discountCode.trim().toUpperCase());
        discount = discountResponse.data?.discount || discountResponse.data;
      }

      if (!discount) {
        setDiscountError('Discount code not found');
        return;
      }

      // Validate discount
      const validationResponse = await discountsAPI.validate({
        discount_code: discount.code || discountCode.trim().toUpperCase(),
        customer_id: null, // Walk-in customers only - customer registration removed
      });

      if (!validationResponse.data?.isValid) {
        setDiscountError(validationResponse.data?.message || 'Discount is not valid');
        return;
      }

      // Apply discount to calculate amount
      const saleItemsForDiscount = cartItems.map(item => ({
        product_id: item.product_id,
        variant_id: item.variant_id || null,
        quantity: item.quantity,
        unit_price: item.unit_price,
      }));

      const applyResponse = await discountsAPI.apply({
        discount_code: discount.code || discountCode.trim().toUpperCase(),
        sale_items: saleItemsForDiscount,
        customer_id: null, // Walk-in customers only - customer registration removed
      });

      const discountResult = applyResponse.data || applyResponse;
      
      if (discountResult.totalDiscountAmount) {
        setAppliedDiscount(discount);
        setDiscountAmount(parseFloat(discountResult.totalDiscountAmount));
        setDiscountError('');
        toast.success('Discount applied successfully');
      } else {
        setDiscountError('Discount could not be applied to cart items');
      }
    } catch (error) {
      console.error('Discount application error:', error);
      setDiscountError(error.response?.data?.message || error.message || 'Failed to apply discount');
      setAppliedDiscount(null);
      setDiscountAmount(0);
    }
  };

  // Handle discount removal
  const handleRemoveDiscount = () => {
    setDiscountCode('');
    setAppliedDiscount(null);
    setDiscountAmount(0);
    setDiscountError('');
  };

  // Handle barcode/UID scan
  const handleBarcodeScan = async (uidOrBarcode) => {
    if (!uidOrBarcode || !uidOrBarcode.trim()) {
      return;
    }

    const scannedUID = uidOrBarcode.trim();
    setIsScanning(true);
    setBarcodeInput('');

    try {
      // If in removal mode, handle removal first
      if (isRemovalMode) {
        // Find item that contains this UID in its scanned_uids array
        const itemToRemove = cartItems.find(
          (item) => item.added_via === 'scan' && item.scanned_uids?.includes(scannedUID)
        );

        if (itemToRemove) {
          // Remove this specific UID from the item
          const updatedUids = itemToRemove.scanned_uids.filter(uid => uid !== scannedUID);
          
          if (updatedUids.length === 0) {
            // No more UIDs, remove entire item
            handleRemoveItem(itemToRemove);
            toast.success(`Removed ${itemToRemove.product_name || 'item'} from cart`);
          } else {
            // Update quantity and UIDs
            const updatedItem = {
              ...itemToRemove,
              scanned_uids: updatedUids,
              quantity: updatedUids.length,
            };
            setCartItems(
              cartItems.map((item) => (item.id === itemToRemove.id ? updatedItem : item))
            );
            toast.success(`Removed 1 item. ${updatedUids.length} remaining.`);
          }
          setIsRemovalMode(false);
          setIsScanning(false);
          return;
        } else {
          toast.error('UID not found in cart. Item may have been added manually.');
          setIsRemovalMode(false);
          setIsScanning(false);
          return;
        }
      }

      // Scan inventory item by UID/barcode
      const scanResponse = await inventoryAPI.scanItem(scannedUID);
      const scannedItem = scanResponse.data?.inventoryItem || scanResponse.data?.item || scanResponse.data;

      if (!scannedItem || !scannedItem.product) {
        toast.error('Product not found for this UID/barcode');
        setIsScanning(false);
        return;
      }

      // Check if item is available (status IN_STOCK)
      if (scannedItem.status !== 'IN_STOCK') {
        toast.error(`Item status: ${scannedItem.status}. Only IN_STOCK items can be sold.`);
        setIsScanning(false);
        return;
      }

      // Get product details
      const product = scannedItem.product;
      const productName = product.name || 'Unknown Product';
      
      // Check if product is sellable (FG and sell_on_pos)
      if (product.product_type !== 'FG' || !product.sell_on_pos) {
        toast.error('This product cannot be sold at POS. Raw materials require manager approval.');
        setIsScanning(false);
        return;
      }

      // Check if this UID is already in cart (prevent duplicates)
      const existingUIDItem = cartItems.find(
        (item) => item.added_via === 'scan' && item.scanned_uids?.includes(scannedUID)
      );

      if (existingUIDItem) {
        toast.error(`UID ${scannedUID} is already in cart. Cannot add duplicate.`, { duration: 3000 });
        setIsScanning(false);
        return;
      }

      // Get price for the product
      let unitPrice = product.selling_price || 0;
      
      // Try to get price from price list if available
      try {
        const priceResponse = await productsAPI.list({
          ids: [product.id],
          include: ['prices'],
          limit: 1,
        });
        const products = priceResponse.data?.products || priceResponse.data?.data || [];
        if (products[0]?.price?.amount) {
          unitPrice = products[0].price.amount;
        }
      } catch (error) {
        // Use selling_price as fallback
      }

      if (!unitPrice || unitPrice <= 0) {
        toast.error('Product price not set. Please set a price before selling.');
        setIsScanning(false);
        return;
      }

      // Check if same product (same product_id and variant_id) already exists in cart
      const existingProductItem = cartItems.find(
        (item) => item.product_id === product.id && 
                  item.variant_id === (scannedItem.variant_id || null) &&
                  item.added_via === 'scan'
      );

      if (existingProductItem) {
        // Same product, different UID - increment quantity and add UID to array
        const updatedItem = {
          ...existingProductItem,
          scanned_uids: [...(existingProductItem.scanned_uids || []), scannedUID],
          quantity: existingProductItem.quantity + 1,
        };
        setCartItems(
          cartItems.map((item) => (item.id === existingProductItem.id ? updatedItem : item))
        );
        toast.success(`${productName} added (${updatedItem.quantity} total)`, { duration: 2000 });
      } else {
        // Different product or first scan - add new item to cart
        const newItemId = `temp-${Date.now()}-${Math.random()}`;
        const newItem = {
          id: newItemId,
          product_id: product.id,
          product_name: productName,
          variant_id: scannedItem.variant_id || null,
          quantity: 1,
          unit_price: unitPrice,
          product: product,
          inventory_item_id: scannedItem.id, // Store inventory_item_id for UID traceability
          added_via: 'scan', // Track that this was added via scan
          scanned_uids: [scannedUID], // Track all scanned UIDs for this item
        };
        setCartItems([...cartItems, newItem]);
        toast.success(`${productName} added to cart`, { duration: 2000 });
      }
    } catch (error) {
      console.error('Barcode scan error:', error);
      toast.error(error.response?.data?.message || error.message || 'Failed to scan barcode/UID');
    } finally {
      setIsScanning(false);
      // Focus back on barcode input for next scan
      setTimeout(() => {
        barcodeInputRef.current?.focus();
      }, 100);
    }
  };

  // Handle barcode input submission (Enter key or button click)
  const handleBarcodeSubmit = (e) => {
    e?.preventDefault();
    if (barcodeInput.trim()) {
      handleBarcodeScan(barcodeInput);
    }
  };

  // Handle checkout with stock checking and RM approval
  const handleCheckout = async () => {
    if (cartItems.length === 0) {
      toast.error('Cart is empty');
      return;
    }

    // Check for RM products requiring approval
    const rmProducts = await checkRMProducts(cartItems);
    if (rmProducts.length > 0 && !isManagerOrAdmin) {
      setPendingApproval({
        type: 'RM_SALE',
        items: rmProducts,
        reason: '',
      });
      setShowManagerApproval(true);
      return;
    }

    // Check stock for all cart items
    try {
      const itemsToCheck = cartItems.map((item) => ({
        product_id: item.product_id,
        variant_id: item.variant_id || null,
        quantity: item.quantity,
      }));

      const stockCheckResponse = await checkStockMutation.mutateAsync(itemsToCheck);
      const stockResults = stockCheckResponse.data?.results || [];

      // Filter items that have stock issues
      const warnings = stockResults
        .filter(result => result.status !== 'IN_STOCK')
        .map(result => {
          const cartItem = cartItems.find(item => item.product_id === result.product_id);
          return {
            ...result,
            product_name: cartItem?.product_name || 'Unknown Product',
          };
        });

      // If there are stock warnings and user is not manager/admin, show stock warning modal
      // If user is manager/admin, show stock override approval modal
      if (warnings.length > 0) {
        if (isManagerOrAdmin) {
          setPendingApproval({
            type: 'STOCK_OVERRIDE',
            items: warnings,
            reason: '',
          });
          setShowManagerApproval(true);
          return;
        } else {
          setStockWarnings(warnings);
          setShowStockWarning(true);
          return;
        }
      }
    } catch (error) {
      // If stock check fails, proceed anyway (might be network issue)
      console.error('Stock check error:', error);
    }

    // Proceed with sale creation
    proceedWithSaleCreation();
  };

  // Handle payment completion
  const handlePaymentComplete = async (paymentData) => {
    // Verify sale status if we have a current sale ID
    if (currentSaleId) {
      try {
        // Fetch the sale to verify its status
        const saleResponse = await salesAPI.getById(currentSaleId);
        const sale = saleResponse?.data?.sale || saleResponse?.data;
        
        if (sale) {
          if (sale.status === 'PAID') {
            toast.success('Sale completed successfully and marked as PAID!');
          } else {
            console.warn(`Sale ${currentSaleId} status is ${sale.status}, expected PAID`);
            toast.success('Payment processed, but sale status may need verification.');
          }
        }
      } catch (error) {
        console.error('Error verifying sale status:', error);
        toast.success('Payment processed successfully!');
      }
    } else {
      toast.success('Payment processed successfully!');
    }
    
    setCartItems([]);
    // selectedCustomer removed - walk-in customers only
    setCurrentSaleId(null);
  };

  // Handle new sale
  const handleNewSale = () => {
    setCartItems([]);
    // selectedCustomer removed - walk-in customers only
    setCurrentSaleId(null);
    setDiscountCode('');
    setAppliedDiscount(null);
    setDiscountAmount(0);
    setDiscountError('');
  };

  return (
    <div className="h-full flex flex-col bg-gray-50 dark:bg-gray-950 -m-4 sm:-m-4 lg:-m-6">
      {/* Top Bar - Header & Actions */}
      <div className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 px-3 sm:px-4 md:px-6 py-2.5 sm:py-3 md:py-4">
        <div className="flex items-center justify-between gap-2 sm:gap-3">
          <div className="flex items-center gap-2 sm:gap-3 md:gap-4 min-w-0 flex-1">
            <div className="w-9 h-9 sm:w-10 sm:h-10 md:w-12 md:h-12 bg-gradient-to-br from-blue-600 to-indigo-600 rounded-lg sm:rounded-xl md:rounded-2xl flex items-center justify-center text-white shadow-lg shadow-blue-500/30 flex-shrink-0">
              <ShoppingCart className="w-4 h-4 sm:w-5 sm:h-5 md:w-6 md:h-6" />
            </div>
            <div className="min-w-0">
              <h1 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 dark:text-white truncate">
                Point of Sale
              </h1>
              <p className="text-xs sm:text-sm text-gray-500 dark:text-gray-400 mt-0.5 hidden sm:block">
                Select products and process sales
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            {/* Cart Toggle Button - Show on all screens except xl+ (where permanent sidebar exists) */}
            <button
              onClick={() => setShowCart(!showCart)}
              className="xl:hidden relative p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
              title="Toggle cart"
            >
              <ShoppingCart className="w-5 h-5 text-gray-700 dark:text-gray-300" />
              {cartItems.length > 0 && (
                <span className="absolute -top-1 -right-1 w-5 h-5 bg-emerald-600 text-white text-xs font-bold rounded-full flex items-center justify-center">
                  {cartItems.length}
                </span>
              )}
            </button>
            {cartItems.length > 0 && (
              <Button 
                variant="outline" 
                onClick={handleNewSale}
                className="hidden sm:flex items-center gap-2"
                size="sm"
              >
                <RotateCcw className="w-4 h-4" />
                <span className="hidden md:inline">New Sale</span>
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col md:flex-row gap-3 md:gap-4 lg:gap-6 overflow-hidden min-h-0 px-3 sm:px-4 md:px-6 py-3 sm:py-4 relative">
        {/* Categories toggle (tab-style): only show when categories are hidden */}
        {!showCategories && (
          <button
            onClick={() => setShowCategories(true)}
            className="
              absolute left-0 top-1/2 -translate-y-1/2 z-20
              flex items-center justify-center
              w-10 h-12
              bg-white dark:bg-gray-900
              border border-gray-300 dark:border-gray-700
              rounded-r-xl
              shadow-md hover:shadow-lg
              hover:bg-gray-50 dark:hover:bg-gray-800
              transition-all
              text-gray-700 dark:text-gray-300
            "
            title="Show Categories"
            aria-label="Show Categories"
          >
            <Tag className="w-4 h-4" />
          </button>
        )}

        {/* Categories Drawer (overlay) - keeps product grid width stable on md/lg */}
        {showCategories && (
          <div className="fixed inset-0 z-40">
            {/* Backdrop */}
            <div
              className="absolute inset-0 bg-black/40 backdrop-blur-[1px]"
              onClick={() => setShowCategories(false)}
            />
            {/* Panel */}
            <div className="absolute left-0 top-0 bottom-0 w-[320px] sm:w-[360px] bg-white dark:bg-gray-900 shadow-2xl border-r border-gray-200 dark:border-gray-800">
              <div className="h-16 flex items-center justify-between px-4 border-b border-gray-200 dark:border-gray-800">
                <div className="flex items-center gap-2 text-gray-900 dark:text-white font-semibold">
                  <Tag className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                  Categories
                </div>
                <button
                  onClick={() => setShowCategories(false)}
                  className="p-2 rounded-lg text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                  title="Close categories"
                  aria-label="Close categories"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
              <div className="h-[calc(100vh-4rem)] p-4">
                <CategorySidebar
                  selectedCategoryId={selectedCategoryId}
                  onCategorySelect={(id) => {
                    setSelectedCategoryId(id);
                    // keep categories open; user can close when ready
                  }}
                />
              </div>
            </div>
          </div>
        )}

        {/* Center - Product Grid (always full width, never shrinks) */}
        <div className="flex-1 overflow-hidden min-w-0 min-h-0 relative">
          <ProductGrid
            onProductSelect={handleProductSelect}
            selectedCategoryId={selectedCategoryId}
          />
        </div>

        {/* Desktop Cart Toggle Button (when collapsed) - only on very large screens (xl+) */}
        {rightSidebarCollapsed && (
          <div className="hidden xl:flex items-start pt-1">
            <button
              onClick={() => setRightSidebarCollapsed(false)}
              className="p-3 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-lg hover:from-emerald-700 hover:to-teal-700 shadow-lg transition-all relative"
              title="Show cart"
            >
              <ShoppingCart className="w-5 h-5" />
              {cartItems.length > 0 && (
                <span className="absolute -top-1 -right-1 w-5 h-5 bg-white text-emerald-600 text-xs font-bold rounded-full flex items-center justify-center animate-pulse">
                  {cartItems.length}
                </span>
              )}
            </button>
          </div>
        )}

        {/* Right Sidebar - Cart (Desktop only, ≥1280px, collapsible & shrinkable) */}
        {!rightSidebarCollapsed && (
          <div className="hidden xl:flex flex-shrink-0 flex-col gap-4 transition-all duration-300 w-80 xl:w-96">
            {/* Cart Header with Close Button */}
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Shopping Cart</h3>
              <button
                onClick={() => setRightSidebarCollapsed(true)}
                className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
                title="Hide cart"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Cart with Integrated Scanner */}
            <div className="flex-1 min-h-0 flex flex-col">
              <Cart
                items={cartItems}
                onUpdateQuantity={handleUpdateQuantity}
                onRemoveItem={handleRemoveItem}
                subtotal={subtotal}
                tax={tax}
                discount={discount}
                total={total}
                discountCode={discountCode}
                onDiscountCodeChange={setDiscountCode}
                onApplyDiscount={handleApplyDiscount}
                itemDiscounts={itemDiscounts}
                onItemDiscountChange={handleItemDiscountChange}
                cartDiscounts={cartDiscounts}
                discountError={discountError}
                appliedDiscount={appliedDiscount}
                onRemoveDiscount={handleRemoveDiscount}
                onEnableRemovalMode={(item) => {
                  setIsRemovalMode(true);
                  toast(`Removal mode enabled. Scan UID to remove from ${item.product_name || 'item'}`, { 
                    duration: 3000,
                    icon: '🔍',
                  });
                  setTimeout(() => {
                    barcodeInputRef.current?.focus();
                  }, 100);
                }}
                // Scanner props
                barcodeInput={barcodeInput}
                onBarcodeInputChange={(e) => setBarcodeInput(e.target.value)}
                onBarcodeSubmit={handleBarcodeSubmit}
                barcodeInputRef={barcodeInputRef}
                isScanning={isScanning}
                isRemovalMode={isRemovalMode}
                onCancelRemovalMode={() => setIsRemovalMode(false)}
                mode="desktop"
              />
            </div>

            {/* Checkout Button */}
            <Button
              variant="primary"
              size="lg"
              className="w-full py-4 text-lg font-bold bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 shadow-lg shadow-emerald-500/30 transition-all duration-200 hover:scale-[1.02] active:scale-[0.98]"
              onClick={handleCheckout}
              disabled={cartItems.length === 0 || createSaleMutation.isPending}
              loading={createSaleMutation.isPending}
            >
              <CreditCard className="w-5 h-5 mr-2" />
              Checkout - {formatCurrency(total)}
            </Button>
          </div>
        )}

        {/* Mobile & Medium Screen Cart Drawer (overlay) */}
        {showCart && (
          <div className="xl:hidden fixed inset-0 z-50">
            {/* Backdrop */}
            <div 
              className="absolute inset-0 bg-black/50 backdrop-blur-sm"
              onClick={() => setShowCart(false)}
            />
            {/* Cart Panel */}
            <div className="absolute right-0 top-0 bottom-0 w-full sm:w-96 md:w-[420px] bg-white dark:bg-gray-900 shadow-2xl flex flex-col animate-in slide-in-from-right">
              {/* Mobile Cart Header */}
              <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-800 bg-gradient-to-r from-emerald-600 to-teal-600 flex items-center justify-between">
                <h3 className="font-bold text-white text-lg">Cart</h3>
                <button
                  onClick={() => setShowCart(false)}
                  className="p-2 text-white hover:bg-white/20 rounded-lg transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Cart Content */}
              <div className="flex-1 overflow-hidden flex flex-col">
                {/* Customer Selection removed - walk-in customers only */}
              <div className="flex-1 min-h-0 px-4 pb-4 overflow-y-auto">
                  <Cart
                    items={cartItems}
                    onUpdateQuantity={handleUpdateQuantity}
                    onRemoveItem={handleRemoveItem}
                    subtotal={subtotal}
                    tax={tax}
                    discount={discount}
                    total={total}
                    discountCode={discountCode}
                    onDiscountCodeChange={setDiscountCode}
                    onApplyDiscount={handleApplyDiscount}
                    itemDiscounts={itemDiscounts}
                    onItemDiscountChange={handleItemDiscountChange}
                    cartDiscounts={cartDiscounts}
                    discountError={discountError}
                    appliedDiscount={appliedDiscount}
                    onRemoveDiscount={handleRemoveDiscount}
                    onEnableRemovalMode={(item) => {
                      setIsRemovalMode(true);
                      toast(`Removal mode enabled. Scan UID to remove from ${item.product_name || 'item'}`, { 
                        duration: 3000,
                        icon: '🔍',
                      });
                      setTimeout(() => {
                        barcodeInputRef.current?.focus();
                      }, 100);
                    }}
                    // Scanner props
                    barcodeInput={barcodeInput}
                    onBarcodeInputChange={(e) => setBarcodeInput(e.target.value)}
                    onBarcodeSubmit={handleBarcodeSubmit}
                    barcodeInputRef={barcodeInputRef}
                    isScanning={isScanning}
                    isRemovalMode={isRemovalMode}
                    onCancelRemovalMode={() => setIsRemovalMode(false)}
                    mode="drawer"
                  />
                </div>
                {/* Mobile Checkout Button */}
                <div className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900">
                  <Button
                    variant="primary"
                    size="lg"
                    className="w-full py-4 text-lg font-bold bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 shadow-lg shadow-emerald-500/30"
                    onClick={handleCheckout}
                    disabled={cartItems.length === 0 || createSaleMutation.isPending}
                    loading={createSaleMutation.isPending}
                  >
                    <CreditCard className="w-5 h-5 mr-2" />
                    Checkout - {formatCurrency(total)}
                  </Button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Payment Modal */}
      <PaymentModal
        isOpen={showPaymentModal}
        onClose={() => {
          setShowPaymentModal(false);
          if (!currentSaleId) {
            handleNewSale();
          }
        }}
        total={total}
        saleId={currentSaleId}
        onPaymentComplete={handlePaymentComplete}
        onManualMPesaConfirm={(paymentId) => {
          setPendingMPesaPaymentId(paymentId);
          setShowManualMPesaConfirm(true);
        }}
      />

      {/* Stock Warning Modal */}
      <StockWarningModal
        isOpen={showStockWarning}
        onClose={() => {
          setShowStockWarning(false);
          setPendingProduct(null);
          setStockWarnings([]);
        }}
        onProceed={handleProceedWithStockWarning}
        warnings={stockWarnings}
      />

      {/* Manager Approval Modal */}
      <ManagerApprovalModal
        isOpen={showManagerApproval}
        onClose={() => {
          setShowManagerApproval(false);
          setPendingApproval({ type: null, items: [], reason: '' });
        }}
        onApprove={handleManagerApproval}
        items={pendingApproval.items}
        approvalType={pendingApproval.type}
        stockOverrideReason={pendingApproval.reason}
        onReasonChange={(reason) => {
          setPendingApproval(prev => ({ ...prev, reason }));
        }}
      />

      {/* Manual M-Pesa Confirmation Modal */}
      <ManualMPesaConfirmModal
        isOpen={showManualMPesaConfirm}
        onClose={() => {
          setShowManualMPesaConfirm(false);
          setPendingMPesaPaymentId(null);
        }}
        paymentId={pendingMPesaPaymentId}
        onConfirm={(payment) => {
          toast.success('Payment confirmed successfully!');
          handlePaymentComplete(payment);
        }}
      />
    </div>
  );
}
