'use client';
import React, { useEffect, useState, useMemo } from 'react';
import { Search, User, Trash2, CreditCard, Banknote, QrCode, Plus, Minus, Filter, X, Pencil, ShoppingCart, Upload, ChevronLeft, ChevronRight } from 'lucide-react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { handlePrintReceipt } from '@/utils/printReceipt';
import { useGlobalContext } from '@/context/Provider';
import DashboardLayout from '@/app/dashboard/layout';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import CustomerModal from '@/components/pos/CustomerModal';
import CustomerSearch from '@/components/pos/CustomerSearch';
import { currency } from '@/lib/utils';

enum PaymentType {
    CashOnDelivery = "cash",
    Card = 'card',
    Wallet = 'wallet',
    UPI = 'upi'
}

interface GroceryItem {
    _id: string;
    name: string;
    price: number;
    description?: string;
    imageUrl?: string;
    stock?: number;
    quantity?: number;
    unit?: string;
    category_id?: any;
}

interface CartItem extends GroceryItem {
    cartId: string;
    qty: number;
    finalPrice: number;
}

export default function GroceryPOSPage() {
    const { userInfo, Toast } = useGlobalContext();
    const rawType = userInfo?.restaurant_id?.type || 'grocery';
    const [groceryItems, setGroceryItems] = useState<GroceryItem[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('All Categories');
    const [categoriesList, setCategoriesList] = useState<{ id: string; name: string }[]>([]);
    const [cart, setCart] = useState<CartItem[]>([]);
    const cartRef = React.useRef<CartItem[]>([]);
    useEffect(() => {
        cartRef.current = cart;
    }, [cart]);
    const [configData, setConfigData] = useState<any>(null);
    const [paymentMethod, setPaymentMethod] = useState<'Cash' | 'Card' | 'UPI'>('Cash');

    const categoryScrollRef = React.useRef<HTMLDivElement>(null);
    const [showLeftArrow, setShowLeftArrow] = useState(false);
    const [showRightArrow, setShowRightArrow] = useState(false);

    const checkScrollState = () => {
        if (categoryScrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = categoryScrollRef.current;
            setShowLeftArrow(scrollLeft > 5);
            setShowRightArrow(scrollLeft + clientWidth < scrollWidth - 5);
        }
    };

    useEffect(() => {
        const timer = setTimeout(checkScrollState, 100);
        window.addEventListener('resize', checkScrollState);
        return () => {
            clearTimeout(timer);
            window.removeEventListener('resize', checkScrollState);
        };
    }, [categoriesList]);

    const scrollCategories = (direction: 'left' | 'right') => {
        if (categoryScrollRef.current) {
            const { scrollLeft, clientWidth } = categoryScrollRef.current;
            const scrollAmount = clientWidth * 0.6;
            categoryScrollRef.current.scrollTo({
                left: direction === 'left' ? scrollLeft - scrollAmount : scrollLeft + scrollAmount,
                behavior: 'smooth'
            });
            setTimeout(checkScrollState, 300);
        }
    };

    const [isCustomerModalOpen, setIsCustomerModalOpen] = useState(false);
    const [customerDetails, setCustomerDetails] = useState<{
        _id?: string;
        name: string;
        phone?: string;
        email?: string;
        gst?: string;
        country_code?: string;
        customer_id?: string;
    }>({
        _id: '',
        name: '',
        phone: '',
        email: '',
        gst: '',
        country_code: '+91',
        customer_id: ''
    });

    useEffect(() => {
        if (typeof window !== 'undefined') {
            const params = new URLSearchParams(window.location.search);
            const name = params.get('name');
            const phone = params.get('phone');
            const email = params.get('email');
            const countryCode = params.get('country_code');
            const customerId = params.get('customer_id');
            if (name || phone || email) {
                setCustomerDetails({
                    _id: customerId || '',
                    name: name || '',
                    phone: phone || '',
                    email: email || '',
                    gst: '',
                    country_code: countryCode ? (countryCode.startsWith('+') ? countryCode : `+${countryCode}`) : '+91'
                });
            }
        }
    }, []);

    // Discount State
    const [discountType, setDiscountType] = useState<'percentage' | 'fixed'>('percentage');
    const [discountValue, setDiscountValue] = useState<number>(0);
    const [isDiscountModalOpen, setIsDiscountModalOpen] = useState(false);
    const [tempDiscountValue, setTempDiscountValue] = useState<number>(0);
    const [tempDiscountType, setTempDiscountType] = useState<'percentage' | 'fixed'>('percentage');

    // Tax State
    const [customTaxPercentage, setCustomTaxPercentage] = useState<number | null>(null);
    const [isTaxModalOpen, setIsTaxModalOpen] = useState(false);
    const [tempTaxPercentage, setTempTaxPercentage] = useState<number>(0);

    // Mobile Tab State
    const [activeTab, setActiveTab] = useState<'menu' | 'cart'>('menu');
    const [isClearCartModalOpen, setIsClearCartModalOpen] = useState(false);

    // Reset discount if cart becomes empty
    useEffect(() => {
        if (cart.length === 0) {
            if (discountValue !== 0) {
                setDiscountValue(0);
                setDiscountType('percentage');
                setTempDiscountValue(0);
                setTempDiscountType('percentage');
            }
        }
    }, [cart.length, discountValue]);

    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isFetchingMore, setIsFetchingMore] = useState(false);
    const observerTarget = React.useRef(null);

    // Fetch Grocery Items and Categories
    const fetchCategories = async () => {
        try {
            const storeId = userInfo?.restaurant_id?._id;
            let query = `limit=1000&type=${rawType}`;
            if (storeId) query += `&store_id=${storeId}`;

            const res = await apis.category.list(query);
            if (res?.data) {
                setCategoriesList(res.data.map((cat: any) => ({ id: cat._id, name: cat.category_name || cat.name })));
            }
        } catch (error) {
            console.error('Error fetching categories:', error);
        }
    };

    const fetchGroceryItems = async (p: number, categoryId?: string, search?: string, isAppend: boolean = false) => {
        if (!isAppend) setLoading(true);
        else setIsFetchingMore(true);

        try {
            const store_id = userInfo?.restaurant_id?._id;
            const catId = categoryId || selectedCategory;
            const sQuery = search !== undefined ? search : searchQuery;

            let query = `page=${p}&limit=20&is_pos=true`;
            if (store_id) query += `&store_id=${store_id}`;
            if (catId && catId !== 'All Categories') {
                query += `&category_id=${catId}`;
            }
            if (sQuery) {
                query += `&search=${sQuery}`;
            }

            const res = await apis.Item.list(query);
            if (res?.success) {
                if (isAppend) {
                    setGroceryItems(prev => [...prev, ...res.data]);
                } else {
                    setGroceryItems(res.data);
                }
                setHasMore(res.pagination.page < res.pagination.totalPages);
                setPage(res.pagination.page);
            }
        } catch (error) {
            Toast.error(error);
        } finally {
            setLoading(false);
            setIsFetchingMore(false);
        }
    };

    const fetchConfiguration = async () => {
        try {
            const res = await apis.Configuration.getConfiguration();
            setConfigData(res?.data?.[0]);
        } catch (error) {
            console.error('Error fetching configuration:', error);
        }
    };

    useEffect(() => {
        if (userInfo?.restaurant_id?._id) {
            fetchCategories();
            fetchGroceryItems(1, selectedCategory, searchQuery, false);
            fetchConfiguration();
        }
    }, [userInfo?.restaurant_id?._id]);

    // Handle Search and Category change
    useEffect(() => {
        if (userInfo?.restaurant_id?._id) {
            const timer = setTimeout(() => {
                fetchGroceryItems(1, selectedCategory, searchQuery, false);
            }, 500);
            return () => clearTimeout(timer);
        }
    }, [searchQuery, selectedCategory]);

    // Intersection Observer for Infinite Scroll
    useEffect(() => {
        const observer = new IntersectionObserver(
            entries => {
                if (entries[0].isIntersecting && hasMore && !isFetchingMore && !loading) {
                    fetchGroceryItems(page + 1, selectedCategory, searchQuery, true);
                }
            },
            { threshold: 1.0 }
        );

        if (observerTarget.current) {
            observer.observe(observerTarget.current);
        }

        return () => {
            if (observerTarget.current) {
                observer.unobserve(observerTarget.current);
            }
        };
    }, [hasMore, isFetchingMore, loading, page, selectedCategory, searchQuery]);

    const barcodeRef = React.useRef<string>('');
    const lastKeyTimeRef = React.useRef<number>(0);

    const handleBarcodeScanned = async (barcodeId: string) => {
        if (!barcodeId) return;
        setLoading(true);
        try {
            const res = await apis.Item.details(barcodeId);
            if (res?.success && res?.data) {
                const item = res.data;

                const existingItem = cartRef.current.find(c => c._id === item._id);
                const currentQty = existingItem ? existingItem.qty : 0;

                if (item.stock !== undefined && item.stock !== null) {
                    if (currentQty + 1 > item.stock) {
                        Toast.error(`Cannot add more than available stock (${item.stock})`);
                        return;
                    }
                }

                const newItem: CartItem = {
                    ...item,
                    cartId: item._id,
                    qty: 1,
                    finalPrice: item.price
                };

                setCart(prev => {
                    const existingIndex = prev.findIndex(c => c._id === item._id);
                    if (existingIndex !== -1) {
                        const newCart = [...prev];
                        newCart[existingIndex] = { ...newCart[existingIndex], qty: newCart[existingIndex].qty + 1 };
                        return newCart;
                    } else {
                        return [...prev, newItem];
                    }
                });
                Toast.success(`${item.name} added to cart`);
                setSearchQuery('');
            } else {
                Toast.error(`Item not found for barcode: ${barcodeId}`);
            }
        } catch (error: any) {
            Toast.error(error?.response?.body?.message || 'Error fetching item details');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Shift' || e.key === 'Control' || e.key === 'Alt' || e.key === 'Meta') {
                return;
            }

            const activeElement = document.activeElement;
            const isInput = activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA');
            const isSearchInput = activeElement && (activeElement as HTMLInputElement).placeholder === 'Search Here';

            if (isInput && !isSearchInput) {
                return;
            }

            const currentTime = Date.now();
            if (currentTime - lastKeyTimeRef.current > 50) {
                barcodeRef.current = '';
            }
            lastKeyTimeRef.current = currentTime;

            if (e.key === 'Enter') {
                if (isSearchInput) {
                    if (searchQuery) {
                        e.preventDefault();
                        e.stopPropagation();
                        handleBarcodeScanned(searchQuery);
                    }
                } else if (barcodeRef.current.length > 2) {
                    e.preventDefault();
                    e.stopPropagation();
                    const scannedBarcode = barcodeRef.current;
                    barcodeRef.current = '';
                    handleBarcodeScanned(scannedBarcode);
                }
            } else {
                if (e.key.length === 1) {
                    barcodeRef.current += e.key;
                }
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, [searchQuery]);

    const filteredItems = groceryItems;

    // Handle Add to Cart Click
    const handleItemClick = (item: GroceryItem) => {
        const existingItem = cart.find(c => c._id === item._id);
        const currentQty = existingItem ? existingItem.qty : 0;

        if (item.stock !== undefined && item.stock !== null) {
            if (currentQty + 1 > item.stock) {
                Toast.error(`Cannot add more than available stock (${item.stock})`);
                return;
            }
        }

        const newItem: CartItem = {
            ...item,
            cartId: item._id, // Use item ID as cartId for groceries since no variants
            qty: 1,
            finalPrice: item.price
        };

        setCart(prev => {
            const existingIndex = prev.findIndex(c => c._id === item._id);
            if (existingIndex !== -1) {
                const newCart = [...prev];
                newCart[existingIndex] = { ...newCart[existingIndex], qty: newCart[existingIndex].qty + 1 };
                return newCart;
            } else {
                return [...prev, newItem];
            }
        });
        Toast.success('Added to cart');
    };

    const updateQuantity = (cartId: string, delta: number) => {
        const item = cart.find(c => c.cartId === cartId);
        if (!item) return;

        if (delta > 0 && item.stock !== undefined && item.stock !== null) {
            if (item.qty + delta > item.stock) {
                Toast.error(`Cannot add more than available stock (${item.stock})`);
                return;
            }
        }

        setCart((prev) =>
            prev.map((item) => {
                if (item.cartId === cartId) {
                    const newQty = Math.max(1, item.qty + delta);
                    return { ...item, qty: newQty };
                }
                return item;
            })
        );
    };

    const removeFromCart = (cartId: string) => {
        setCart((prev) => {
            const next = prev.filter((item) => item.cartId !== cartId);
            if (next.length === 0) {
                setDiscountValue(0);
                setDiscountType('percentage');
                setTempDiscountValue(0);
                setTempDiscountType('percentage');
            }
            return next;
        });
    };

    const handlePlaceOrder = async () => {
        if (cart.length === 0) {
            Toast.error('Cart is empty');
            return;
        }

        const payload = {
            restaurant_id: userInfo?.restaurant_id?._id,
            other_cart_items: cart.map(item => ({
                item_id: item._id, // For grocery, use item_id instead of food_id
                name: item.name,
                no_of_quantity: item.qty,
                price: item.price,
                unit: item.unit,
                quantity: item.quantity,
                add_ons: [],
                make_your_own: [],
                toppings: [],
            })),
            add_receiver_detail: {
                name: customerDetails.name || 'Walk-in Customer',
                phone: customerDetails.phone || '',
                email: customerDetails.email || '',
                gst_no: customerDetails.gst || '',
                country_code: (customerDetails.country_code || '+91').replace('+', ''),
                customer_id: customerDetails._id || ''
            },
            payment_type: paymentMethod === 'Cash' ? PaymentType.CashOnDelivery :
                paymentMethod === 'Card' ? PaymentType.Card :
                    paymentMethod === 'UPI' ? PaymentType.UPI : PaymentType.CashOnDelivery,
            cart_amount: subTotal,
            platform_fee: 0,
            tax_amount: tax,
            coupon_amount: discountAmount,
            total_amount: total,
            sales_commission: salesCommissionAmount,
            order_type: 'pos',
            is_grocery: true // Added to distinguish grocery orders
        };

        setLoading(true);
        try {
            const res = await apis.Orders.placed(payload);
            if (res) {
                Toast.success('Order placed successfully');
                // Trigger Thermal Print
                handlePrintReceipt(res.data || res, userInfo?.restaurant_id, currency, configData);
                setCart([]);
                setCustomerDetails({ _id: '', name: '', phone: '', email: '', gst: '', country_code: '+91' });
                setDiscountValue(0);
                setDiscountType('percentage');
                setCustomTaxPercentage(null);
            }
        } catch (error: any) {
            Toast.error(error?.response?.body?.message || 'Error placing order');
        } finally {
            setLoading(false);
        }
    };

    const handleSendToCustomer = async () => {
        if (cart.length === 0) {
            Toast.error('Cart is empty');
            return;
        }

        if (!customerDetails._id) {
            Toast.error('Please select a customer to send items');
            return;
        }

        const payload = {
            customer_id: customerDetails._id,
            other_cart_items: cart.map(item => ({
                id: item._id,
                no_of_quantity: item.qty
            })),
        };

        setLoading(true);
        try {
            const res = await apis.Customer.itemsForCustomer(payload);
            if (res) {
                Toast.success('Items sent to customer successfully');
                setCart([]);
                setCustomerDetails({ _id: '', name: '', phone: '', email: '', gst: '', country_code: '+91' });
                setDiscountValue(0);
                setDiscountType('percentage');
                setCustomTaxPercentage(null);
            }
        } catch (error: any) {
            Toast.error(error?.response?.body?.message || 'Error sending items to customer');
        } finally {
            setLoading(false);
        }
    };

    // Calculations
    const taxConfig = userInfo?.appConfigDetails?.[0]?.tax || userInfo?.restaurant_id?.tax;
    const taxPercentage = customTaxPercentage !== null ? customTaxPercentage : Number(taxConfig?.tax_percentage || 0);
    const taxKeyword = taxConfig?.tax_keyword || 'Tax';
    // const salesCommissionPercentage = Number(configData?.sales_commission_percentage || 0);
    const salesCommissionPercentage = 0;

    const subTotal = cart.reduce((acc, item) => acc + (item.finalPrice || item.price) * item.qty, 0);
    const rawDiscountAmount = discountType === 'percentage' ? (subTotal * discountValue) / 100 : discountValue;
    const discountAmount = Math.min(subTotal, Math.max(0, rawDiscountAmount));
    const tax = (subTotal - discountAmount) * (taxPercentage / 100);
    // const salesCommissionAmount = (subTotal - discountAmount) * (salesCommissionPercentage / 100);
    const salesCommissionAmount = 0;
    const total = Math.max(0, subTotal - discountAmount + tax + salesCommissionAmount);

    return (
        <DashboardLayout>
            <div className="flex flex-col h-[calc(100vh-140px)] w-full gap-4 bg-gray-50 p-2 md:p-4 lg:flex-row overflow-hidden">

                {/* Mobile Tab Switcher */}
                <div className="flex w-full gap-2 lg:hidden">
                    <Button
                        onClick={() => setActiveTab('menu')}
                        className={`flex-1 ${activeTab === 'menu' ? 'bg-[var(--orange-500)] text-white' : 'bg-white text-gray-600'}`}
                    >
                        Items
                    </Button>
                    <Button
                        onClick={() => setActiveTab('cart')}
                        className={`flex-1 ${activeTab === 'cart' ? 'bg-[var(--orange-500)] text-white' : 'bg-white text-gray-600'}`}
                    >
                        Cart ({cart.reduce((acc, item) => acc + item.qty, 0)})
                    </Button>
                </div>

                {/* LEFT COLUMN - MENU */}
                <div className={`${activeTab === 'menu' ? 'flex' : 'hidden'} lg:flex flex-[1.5] flex-col gap-4 overflow-hidden rounded-xl bg-white p-3 shadow-sm md:p-4`}>
                    {/* Header */}
                    <div className="flex flex-col gap-3">
                        {/* Categories List with scroll arrows */}
                        <div className="relative flex items-center group w-full px-1">
                            {showLeftArrow && (
                                <button
                                    type="button"
                                    onClick={() => scrollCategories('left')}
                                    className="flex absolute left-0 z-10 items-center justify-center h-8 w-8 rounded-full bg-white shadow-md border border-gray-200 text-gray-700 hover:bg-gray-100 transition-all cursor-pointer -ml-1 shrink-0"
                                    aria-label="Scroll left"
                                >
                                    <ChevronLeft size={18} />
                                </button>
                            )}

                            <div
                                ref={categoryScrollRef}
                                onScroll={checkScrollState}
                                onWheel={(e) => {
                                    if (categoryScrollRef.current && e.deltaY !== 0) {
                                        categoryScrollRef.current.scrollLeft += e.deltaY;
                                        checkScrollState();
                                    }
                                }}
                                className={`flex items-center gap-2 overflow-x-auto py-1 no-scrollbar w-full scroll-smooth ${showLeftArrow ? 'pl-8' : 'pl-0'
                                    } ${showRightArrow ? 'pr-8' : 'pr-0'}`}
                            >
                                <button
                                    type="button"
                                    onClick={() => setSelectedCategory('All Categories')}
                                    className={`px-4 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all flex-shrink-0 cursor-pointer ${selectedCategory === 'All Categories'
                                        ? 'bg-[var(--orange-500)] text-white shadow-sm'
                                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200 border border-gray-200'
                                        }`}
                                >
                                    All Categories
                                </button>
                                {categoriesList.map((cat) => (
                                    <button
                                        key={cat.id}
                                        type="button"
                                        onClick={() => setSelectedCategory(cat.id)}
                                        className={`px-4 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all flex-shrink-0 cursor-pointer ${selectedCategory === cat.id
                                            ? 'bg-[var(--orange-500)] text-white shadow-sm'
                                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200 border border-gray-200'
                                            }`}
                                    >
                                        {cat.name}
                                    </button>
                                ))}
                            </div>

                            {showRightArrow && (
                                <button
                                    type="button"
                                    onClick={() => scrollCategories('right')}
                                    className="flex absolute right-0 z-10 items-center justify-center h-8 w-8 rounded-full bg-white shadow-md border border-gray-200 text-gray-700 hover:bg-gray-100 transition-all cursor-pointer -mr-1 shrink-0"
                                    aria-label="Scroll right"
                                >
                                    <ChevronRight size={18} />
                                </button>
                            )}
                        </div>

                        <div className="flex items-center gap-2 flex-1">
                            <div className="relative flex-1">
                                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                                <Input
                                    placeholder="Search Here"
                                    className="bg-gray-50 pl-10"
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Grid */}
                    <div className="grid flex-1 grid-cols-1 gap-3 overflow-y-auto pb-4 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-3 custom-scrollbar content-start">
                        {filteredItems.map((item) => {
                            const cartItem = cart.find((c) => c._id === item._id);
                            const totalQty = cartItem?.qty || 0;
                            const isSelected = totalQty > 0;

                            return (
                                <div
                                    key={item._id}
                                    className={`flex h-32 sm:h-36 w-full overflow-hidden rounded-xl border bg-white shadow-sm transition hover:shadow-md ${isSelected ? 'border-[var(--orange-500)] ring-1 ring-[var(--orange-500)]/30 bg-purple-50/10' : 'border-gray-200'
                                        }`}
                                >
                                    {/* Image Section */}
                                    <div className="relative h-full w-20 sm:w-24 shrink-0 bg-gray-100 flex items-center justify-center border-r">
                                        {item.imageUrl ? (
                                            <img
                                                src={`${BUCKET_ROOT}${item.imageUrl}`}
                                                alt={item.name}
                                                className="h-full w-full object-cover"
                                                onError={(e) => { (e.target as any).style.display = 'none' }}
                                            />
                                        ) : (
                                            <Upload className="w-6 h-6 text-gray-400" />
                                        )}
                                    </div>

                                    {/* Content Section */}
                                    <div className="flex flex-1 flex-col justify-between p-2.5 min-w-0">
                                        <div className="space-y-0.5 min-w-0">
                                            <h3 className="font-bold text-sm text-gray-800 truncate" title={item.name}>
                                                {item.name}
                                            </h3>
                                            <p className="text-[10px] text-gray-400 line-clamp-1 leading-tight flex items-center flex-wrap gap-1">
                                                <span>{item.quantity} {item.unit}</span>
                                                {item.stock !== undefined && item.stock !== null && (
                                                    <span className={`px-1 py-0.5 rounded text-[9px] ${item.stock === 0
                                                        ? 'bg-red-100 text-red-700 font-bold'
                                                        : item.stock <= 5
                                                            ? 'bg-amber-100 text-amber-700 font-medium'
                                                            : 'bg-green-50 text-green-700 font-medium'
                                                        }`}>
                                                        {item.stock === 0 ? 'Out of Stock' : `Stock: ${item.stock}`}
                                                    </span>
                                                )}
                                            </p>
                                            <p className="text-[10px] text-gray-500 line-clamp-2 leading-tight h-[26px] overflow-hidden" dangerouslySetInnerHTML={{ __html: item.description || '' }} />
                                        </div>

                                        <div className="flex items-center justify-between gap-1.5 mt-auto pt-1 min-w-0">
                                            <span className="text-sm sm:text-base font-black text-[var(--orange-500)] whitespace-nowrap shrink-0">{currency}{item.price}</span>

                                            <div className="shrink-0">
                                                {isSelected ? (
                                                    <div className="flex items-center h-8 rounded-lg bg-[var(--orange-500)] text-white shadow-md border border-[var(--orange-500)] px-1 transition-all">
                                                        <button
                                                            type="button"
                                                            className="p-1 hover:bg-white/20 rounded text-white transition-colors cursor-pointer shrink-0"
                                                            onClick={() => {
                                                                if (totalQty > 1) {
                                                                    updateQuantity(item._id, -1);
                                                                } else {
                                                                    removeFromCart(item._id);
                                                                }
                                                            }}
                                                        >
                                                            <Minus size={12} className="stroke-[2.5]" />
                                                        </button>
                                                        <span className="text-xs font-black min-w-[16px] text-center text-white px-0.5">{totalQty}</span>
                                                        <button
                                                            type="button"
                                                            className="p-1 hover:bg-white/20 rounded text-white transition-colors cursor-pointer shrink-0"
                                                            onClick={() => handleItemClick(item)}
                                                        >
                                                            <Plus size={12} className="stroke-[2.5]" />
                                                        </button>
                                                    </div>
                                                ) : (
                                                    <button
                                                        type="button"
                                                        className="h-8 w-8 rounded-lg bg-gray-100 border border-gray-300 text-[var(--orange-500)] hover:bg-[var(--orange-500)] hover:text-white hover:border-[var(--orange-500)] flex items-center justify-center transition-all cursor-pointer active:scale-95 shadow-sm"
                                                        onClick={() => handleItemClick(item)}
                                                        title="Add to cart"
                                                    >
                                                        <Plus size={16} className="stroke-[2.5]" />
                                                    </button>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                        {filteredItems.length === 0 && !loading && (
                            <div className="col-span-full flex h-40 flex-col items-center justify-center text-gray-500">
                                <div className="text-lg font-medium">No items found</div>
                            </div>
                        )}
                        {/* Sentinel element for intersection observer */}
                        <div ref={observerTarget} className="col-span-full h-10 flex items-center justify-center">
                            {isFetchingMore && <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[var(--orange-500)]"></div>}
                        </div>
                    </div>
                </div>

                {/* RIGHT COLUMN - CART */}
                <div className={`${activeTab === 'cart' ? 'flex' : 'hidden'} lg:flex w-full lg:w-[420px] flex-col gap-4 rounded-xl bg-white p-3 shadow-sm md:p-4 overflow-y-auto custom-scrollbar border`}>
                    {/* Customer Search */}
                    <div className="flex items-center gap-2">
                        <CustomerSearch
                            selectedValue={customerDetails.name}
                            onSelect={(details) => {
                                setCustomerDetails({
                                    _id: details._id || '',
                                    name: details.name,
                                    phone: details.phone || '',
                                    email: details.email || '',
                                    gst: details.gst || '',
                                    country_code: details.country_code || '+91',
                                    customer_id: details.customer_id || details._id || ''
                                });
                            }}
                            onAddNew={() => {
                                setCustomerDetails({ _id: '', name: '', phone: '', email: '', gst: '', country_code: '+91' });
                                setIsCustomerModalOpen(true);
                            }}
                            onClear={() => {
                                setCustomerDetails({ _id: '', name: '', phone: '', email: '', gst: '', country_code: '+91' });
                            }}
                        />
                        <Button
                            className="bg-[var(--orange-500)] hover:bg-[var(--orange-500)]/90 p-2 h-10 w-10 shrink-0 rounded-xl"
                            onClick={() => setIsCustomerModalOpen(true)}
                        >
                            <User className="h-5 w-5 text-white" />
                        </Button>
                    </div>

                    {/* Cart Items List */}
                    <div className="flex flex-col gap-3 pr-1">
                        {cart.map((item) => (
                            <div key={item.cartId} className="flex items-start gap-3 rounded-2xl border p-3 bg-white group transition-all hover:border-[var(--orange-500)]/30 shadow-sm relative">
                                <div className="h-16 w-16 rounded-xl overflow-hidden shrink-0 border bg-gray-50 flex items-center justify-center">
                                    {item.imageUrl ? (
                                        <img
                                            src={`${BUCKET_ROOT}${item.imageUrl}`}
                                            alt={item.name}
                                            className="h-full w-full object-cover"
                                            onError={(e) => { (e.target as any).style.display = 'none' }}
                                        />
                                    ) : (
                                        <Upload className="w-5 h-5 text-gray-400" />
                                    )}
                                </div>
                                <div className="flex-1 min-w-0 pr-8">
                                    <h4 className="text-sm font-bold text-gray-800 truncate" title={item.name}>{item.name}</h4>
                                    <div className="text-xs text-gray-500">{item.quantity} {item.unit}</div>
                                    <div className="text-sm font-black text-gray-900 mt-0.5">{currency}{(item.finalPrice).toFixed(2)}</div>
                                </div>

                                <button
                                    onClick={() => removeFromCart(item.cartId)}
                                    className="text-red-500 hover:text-red-700 absolute top-3 right-3 p-1 rounded-lg hover:bg-red-50 transition-colors"
                                >
                                    <Trash2 size={16} />
                                </button>

                                <div className="absolute bottom-3 right-3 flex items-center h-8 rounded-lg bg-[var(--orange-500)] text-white shadow-sm border border-[var(--orange-500)] px-1 transition-all">
                                    <button
                                        onClick={() => updateQuantity(item.cartId, -1)}
                                        className="p-1 hover:bg-white/20 rounded text-white transition-colors cursor-pointer shrink-0"
                                    >
                                        <Minus size={12} className="stroke-[2.5]" />
                                    </button>
                                    <span className="text-xs font-black min-w-[18px] text-center text-white px-0.5">{item.qty}</span>
                                    <button
                                        onClick={() => updateQuantity(item.cartId, 1)}
                                        className="p-1 hover:bg-white/20 rounded text-white transition-colors cursor-pointer shrink-0"
                                    >
                                        <Plus size={12} className="stroke-[2.5]" />
                                    </button>
                                </div>
                            </div>
                        ))}
                        {cart.length === 0 && (
                            <div className="flex flex-col items-center justify-center flex-1 text-sm text-gray-400 py-10 opacity-50">
                                <ShoppingCart size={40} className="mb-2" />
                                <p>Cart is empty</p>
                            </div>
                        )}
                    </div>

                    {/* Summary Section */}
                    <div className="mt-auto space-y-4 pt-4 border-t border-dashed">
                        <div className="space-y-2">
                            <div className="flex justify-between text-sm text-gray-600">
                                <span>Total</span>
                                <span className="font-bold text-gray-900">{currency}{subTotal.toFixed(2)}</span>
                            </div>
                            <div className="flex justify-between text-sm text-green-600">
                                <div className="flex items-center gap-1">
                                    <span>Discount {discountValue > 0 ? (discountType === 'percentage' ? `(${discountValue}%)` : `(${currency}${discountValue})`) : ''}</span>
                                    <button
                                        onClick={() => {
                                            setTempDiscountValue(discountValue);
                                            setTempDiscountType(discountType);
                                            setIsDiscountModalOpen(true);
                                        }}
                                        className="text-gray-300 hover:text-green-600 transition-colors"
                                    >
                                        <Pencil size={12} />
                                    </button>
                                </div>
                                <span>-{currency}{discountAmount.toFixed(2)}</span>
                            </div>
                            <div className="flex justify-between text-sm text-gray-600">
                                <div className="flex items-center gap-1">
                                    <span>{taxKeyword} ({taxPercentage}%)</span>
                                    <button
                                        onClick={() => {
                                            setTempTaxPercentage(taxPercentage);
                                            setIsTaxModalOpen(true);
                                        }}
                                        className="text-gray-300 hover:text-gray-600 transition-colors"
                                    >
                                        <Pencil size={12} />
                                    </button>
                                </div>
                                <span>{currency}{tax.toFixed(2)}</span>
                            </div>
                            {/* {salesCommissionPercentage > 0 && (
                                <div className="flex justify-between text-sm text-gray-600">
                                    <span>Sales Commission ({salesCommissionPercentage}%)</span>
                                    <span>{currency}{salesCommissionAmount.toFixed(2)}</span>
                                </div>
                            )} */}
                        </div>

                        <div className="border-t border-dashed border-gray-300 pt-2">
                            <div className="flex justify-between items-center">
                                <span className="text-xl font-black text-gray-900">Total</span>
                                <span className="text-2xl font-black text-[var(--orange-500)]">{currency}{total.toFixed(2)}</span>
                            </div>
                        </div>

                        {/* Payment Methods */}
                        <div className="grid grid-cols-3 gap-2">
                            {[
                                { id: 'Cash', icon: <Banknote size={18} />, label: 'Cash' },
                                { id: 'Card', icon: <CreditCard size={18} />, label: 'Card' },
                                { id: 'UPI', icon: <QrCode size={18} />, label: 'UPI' },
                            ].map((method) => (
                                <button
                                    key={method.id}
                                    onClick={() => setPaymentMethod(method.id as any)}
                                    className={`flex flex-col items-center justify-center gap-1 rounded-xl border p-2 text-[10px] font-bold transition-all ${paymentMethod === method.id
                                        ? 'border-[var(--orange-500)] bg-[var(--orange-50)] text-[var(--orange-500)] shadow-sm'
                                        : 'border-gray-100 bg-white text-gray-500 hover:border-gray-200'
                                        }`}
                                >
                                    {method.icon}
                                    {method.label}
                                </button>
                            ))}
                        </div>

                        {/* Action Buttons */}
                        <div className="flex gap-2.5 pt-2">
                            <Button
                                className="flex-1 bg-[var(--orange-500)] text-white hover:bg-[var(--orange-500)]/90 h-12 text-xs font-bold shadow-lg shadow-[var(--orange-500)]/20"
                                onClick={handlePlaceOrder}
                                disabled={loading || cart.length === 0}
                            >
                                {loading ? 'Placing Order...' : 'Place Order'}
                            </Button>
                            <Button
                                className="flex-1 bg-green-600 text-white hover:bg-green-700 h-12 text-xs font-bold shadow-lg shadow-green-600/20"
                                onClick={handleSendToCustomer}
                                disabled={loading || cart.length === 0}
                            >
                                Send
                            </Button>
                            <Button
                                variant="outline"
                                className="flex-1 border-gray-200 text-gray-500 hover:bg-gray-50 h-12 text-xs font-bold"
                                onClick={() => {
                                    if (cart.length > 0) {
                                        setIsClearCartModalOpen(true);
                                    }
                                }}
                            >
                                Cancel
                            </Button>
                        </div>
                    </div>
                </div>

                {/* MODALS */}
                <CustomerModal
                    isOpen={isCustomerModalOpen}
                    onClose={() => setIsCustomerModalOpen(false)}
                    onSave={async (customer) => {
                        let customerId = customerDetails._id;

                        // If phone or email changed, clear old _id to perform a fresh check
                        const isPhoneChanged = customer.phone !== customerDetails.phone;
                        const isEmailChanged = customer.email?.toLowerCase() !== customerDetails.email?.toLowerCase();
                        if (isPhoneChanged || isEmailChanged) {
                            customerId = '';
                        }

                        // If no customer ID is present, search for matching customer by phone or email
                        if (!customerId && (customer.phone || customer.email)) {
                            try {
                                const searchVal = customer.phone || customer.email || '';
                                const res = await apis.Customer.listing(`search=${encodeURIComponent(searchVal)}&limit=10`);
                                if (res && res.data && res.data.length > 0) {
                                    // Find exact match by phone or email
                                    const match = res.data.find((c: any) =>
                                        (customer.phone && c.phone === customer.phone) ||
                                        (customer.email && c.email?.toLowerCase() === customer.email.toLowerCase())
                                    );
                                    if (match) {
                                        customerId = match._id;
                                    }
                                }
                            } catch (error) {
                                console.error('Error searching for existing customer:', error);
                            }
                        }

                        setCustomerDetails({
                            _id: customerId,
                            name: customer.name,
                            phone: customer.phone || '',
                            email: customer.email || '',
                            gst: customer.gst || '',
                            country_code: customer.country_code || '+91'
                        });
                        setIsCustomerModalOpen(false);
                    }}
                    initialData={customerDetails}
                />

                {/* Discount Modal */}
                {(() => {
                    const discountError = (() => {
                        if (tempDiscountValue < 0) return 'Discount cannot be negative';
                        if (tempDiscountType === 'percentage' && tempDiscountValue > 100) {
                            return 'Discount percentage cannot exceed 100%';
                        }
                        if (tempDiscountType === 'fixed' && subTotal > 0 && tempDiscountValue > subTotal) {
                            return `Discount amount cannot exceed total amount of ${currency}${subTotal.toFixed(2)}`;
                        }
                        if (cart.length === 0 && tempDiscountValue > 0) {
                            return 'Please add items to cart before applying discount';
                        }
                        return '';
                    })();

                    return (
                        <Dialog open={isDiscountModalOpen} onOpenChange={setIsDiscountModalOpen}>
                            <DialogContent className="sm:max-w-[400px]">
                                <DialogHeader>
                                    <DialogTitle>Add Discount</DialogTitle>
                                </DialogHeader>
                                <div className="grid gap-4 py-4">
                                    <div className="flex items-center gap-4">
                                        <Button
                                            variant={tempDiscountType === 'percentage' ? 'theme' : 'outline'}
                                            onClick={() => setTempDiscountType('percentage')}
                                            className="flex-1"
                                        >
                                            Percentage (%)
                                        </Button>
                                        <Button
                                            variant={tempDiscountType === 'fixed' ? 'theme' : 'outline'}
                                            onClick={() => setTempDiscountType('fixed')}
                                            className="flex-1"
                                        >
                                            Fixed Amount ({currency})
                                        </Button>
                                    </div>
                                    <div className="grid gap-2">
                                        <div className="flex items-center justify-between">
                                            <Label htmlFor="discount">Discount Value</Label>
                                            {tempDiscountType === 'percentage' ? (
                                                <span className="text-xs text-gray-400">Max: 100%</span>
                                            ) : subTotal > 0 ? (
                                                <span className="text-xs text-gray-400">Max: {currency}{subTotal.toFixed(2)}</span>
                                            ) : null}
                                        </div>
                                        <Input
                                            id="discount"
                                            type="number"
                                            min="0"
                                            className={discountError ? 'border-red-500 text-red-600 focus-visible:ring-red-500' : ''}
                                            value={tempDiscountValue === 0 ? '' : tempDiscountValue}
                                            onChange={(e) => {
                                                const val = e.target.value;
                                                if (val === '') {
                                                    setTempDiscountValue(0);
                                                    return;
                                                }
                                                const num = Number(val);
                                                if (isNaN(num)) return;
                                                setTempDiscountValue(num);
                                            }}
                                        />
                                        {discountError && (
                                            <p className="text-xs font-semibold text-red-500 mt-1">
                                                {discountError}
                                            </p>
                                        )}
                                    </div>
                                </div>
                                <DialogFooter>
                                    <Button variant="outline" onClick={() => setIsDiscountModalOpen(false)}>Cancel</Button>
                                    <Button
                                        variant="theme"
                                        disabled={!!discountError}
                                        onClick={() => {
                                            if (discountError) return;
                                            setDiscountValue(tempDiscountValue);
                                            setDiscountType(tempDiscountType);
                                            setIsDiscountModalOpen(false);
                                            Toast.success('Discount applied');
                                        }}
                                    >
                                        Apply
                                    </Button>
                                </DialogFooter>
                            </DialogContent>
                        </Dialog>
                    );
                })()}

                {/* Tax Modal */}
                <Dialog open={isTaxModalOpen} onOpenChange={setIsTaxModalOpen}>
                    <DialogContent className="sm:max-w-[400px]">
                        <DialogHeader>
                            <DialogTitle>Edit Tax</DialogTitle>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                            <div className="grid gap-2">
                                <Label htmlFor="tax">Tax Percentage (%)</Label>
                                <Input
                                    id="tax"
                                    type="number"
                                    value={tempTaxPercentage}
                                    onChange={(e) => setTempTaxPercentage(Number(e.target.value))}
                                />
                            </div>
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsTaxModalOpen(false)}>Cancel</Button>
                            <Button variant="theme" onClick={() => {
                                setCustomTaxPercentage(tempTaxPercentage);
                                setIsTaxModalOpen(false);
                            }}>Apply</Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>

                {/* Clear Cart Modal */}
                <Dialog open={isClearCartModalOpen} onOpenChange={setIsClearCartModalOpen}>
                    <DialogContent className="sm:max-w-[400px]">
                        <DialogHeader>
                            <DialogTitle>Clear Cart</DialogTitle>
                        </DialogHeader>
                        <p className="py-4">Are you sure you want to clear the cart? This action cannot be undone.</p>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsClearCartModalOpen(false)}>No, Keep it</Button>
                            <Button variant="destructive" onClick={() => {
                                setCart([]);
                                setDiscountValue(0);
                                setDiscountType('percentage');
                                setTempDiscountValue(0);
                                setTempDiscountType('percentage');
                                setIsClearCartModalOpen(false);
                            }}>Yes, Clear Cart</Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>
        </DashboardLayout>
    );
}
