'use client';
import React, { useEffect, useState, useMemo } from 'react';
import { Search, User, Trash2, CreditCard, Banknote, QrCode, Plus, Minus, Filter, X, Pencil, ShoppingCart } 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 { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import CustomerModal from '@/components/pos/CustomerModal';
import CustomerSearch from '@/components/pos/CustomerSearch';
import { currency } from '@/lib/utils';
import DeleteDialog from '@/components/ui/deleteModal';

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

interface Variant {
    _id: string;
    title: string;
    add_price: number;
    final_price: number;
}

interface AddOn {
    _id: string;
    title: string;
    additional_price: number;
    customer_selection: 'optional' | 'compulsory';
}

interface OtherAddOnGroup {
    _id: string;
    title: string;
    description: string | null;
    options: AddOn[];
}

interface FoodItem {
    _id: string;
    name: string;
    price: number;
    description: string;
    image: string[];
    food_type: 'veg' | 'non_veg';
    category_id: string;
    category_name?: string;
    pieces: Variant[];
    quantity: Variant[];
    size: Variant[];
    add_ons: AddOn[];
    toppings: AddOn[];
    other_add_ons: OtherAddOnGroup[];
}

interface CartItem extends FoodItem {
    cartId: string;
    qty: number;
    selectedVariant?: Variant & { type: 'pieces' | 'quantity' | 'size' };
    selectedAddOns: AddOn[];
    selectedToppings: AddOn[];
    selectedOtherAddOns: AddOn[];
    finalPrice: number;
}

export default function POSPage() {
    const { userInfo, Toast } = useGlobalContext();
    const [foodItems, setFoodItems] = useState<FoodItem[]>([]);
    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 [configData, setConfigData] = useState<any>(null);
    const [paymentMethod, setPaymentMethod] = useState<'Cash' | 'Card' | 'UPI'>('Cash');

    const [selectedItem, setSelectedItem] = useState<FoodItem | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [variantType, setVariantType] = useState<'pieces' | 'quantity' | 'size' | null>(null);
    const [selectedVariantId, setSelectedVariantId] = useState<string>('');
    const [selectedAddOnIds, setSelectedAddOnIds] = useState<string[]>([]);
    const [selectedToppingIds, setSelectedToppingIds] = useState<string[]>([]);
    const [selectedOtherAddOnIds, setSelectedOtherAddOnIds] = useState<string[]>([]);

    const [isCustomerModalOpen, setIsCustomerModalOpen] = useState(false);
    const [customerDetails, setCustomerDetails] = useState({
        name: '',
        phone: '',
        email: '',
        gst: '',
        country_code: '+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);

    // Fetch Food Items and Categories
    const fetchCategories = async () => {
        try {
            const res = await apis.category.get();
            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 fetchFoodItems = async (categoryId?: string) => {
        setLoading(true);
        try {
            const restaurant_id = userInfo?.restaurant_id?._id;
            let query = `limit=1000&catering_services=false`; // Increased limit as per swagger suggestion
            if (restaurant_id) query += `&restaurant_id=${restaurant_id}`;
            if (categoryId && categoryId !== 'All Categories') {
                query += `&category_id=${categoryId}`;
            }

            const res = await apis.FoodList.get(query);
            if (res?.data) {
                setFoodItems(res.data);
            }
        } catch (error) {
            Toast.error(error);
        } finally {
            setLoading(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();
            fetchFoodItems();
            fetchConfiguration();
        }
    }, [userInfo?.restaurant_id?._id]);

    // Filter Items
    const filteredItems = useMemo(() => {
        return foodItems.filter((item) => {
            const matchesSearch = item.name.toLowerCase().includes(searchQuery.toLowerCase());
            return matchesSearch;
        });
    }, [foodItems, searchQuery]);

    // Helper to get variants safely
    const getVariants = (item: FoodItem | null, type: 'pieces' | 'quantity' | 'size' | null): Variant[] => {
        if (!item || !type) return [];
        return (item[type] as Variant[]) || [];
    };

    // Helper to check if two cart items are identical
    const isSameItem = (item1: CartItem, item2: CartItem) => {
        if (item1._id !== item2._id) return false;

        const v1 = item1.selectedVariant?._id;
        const v2 = item2.selectedVariant?._id;
        if (v1 !== v2) return false;

        const a1 = item1.selectedAddOns.map(a => a._id).sort().join(',');
        const a2 = item2.selectedAddOns.map(a => a._id).sort().join(',');
        if (a1 !== a2) return false;

        const t1 = item1.selectedToppings.map(t => t._id).sort().join(',');
        const t2 = item2.selectedToppings.map(t => t._id).sort().join(',');
        if (t1 !== t2) return false;

        const o1 = item1.selectedOtherAddOns.map(o => o._id).sort().join(',');
        const o2 = item2.selectedOtherAddOns.map(o => o._id).sort().join(',');
        if (o1 !== o2) return false;

        return true;
    };

    // Handle Add to Cart Click
    const handleItemClick = (item: FoodItem) => {
        const hasVariants = (item.pieces?.length || 0) > 0 || (item.quantity?.length || 0) > 0 || (item.size?.length || 0) > 0;
        const hasAddOns = (item.add_ons?.length || 0) > 0 || (item.toppings?.length || 0) > 0 || (item.other_add_ons?.length || 0) > 0;

        if (hasVariants || hasAddOns) {
            openCustomizeModal(item);
        } else {
            addToCartDirectly(item);
            Toast.success('Added to cart');
        }
    };

    const openCustomizeModal = (item: FoodItem) => {
        setSelectedItem(item);

        // Determine variant type
        let type: 'pieces' | 'quantity' | 'size' | null = null;
        let defaultVariantId = '';

        if (item.size?.length > 0) {
            type = 'size';
            defaultVariantId = item.size[0]._id;
        } else if (item.quantity?.length > 0) {
            type = 'quantity';
            defaultVariantId = item.quantity[0]._id;
        } else if (item.pieces?.length > 0) {
            type = 'pieces';
            defaultVariantId = item.pieces[0]._id;
        }

        setVariantType(type);
        setSelectedVariantId(defaultVariantId);
        setSelectedAddOnIds([]);
        setSelectedToppingIds([]);
        setSelectedOtherAddOnIds([]);
        setIsModalOpen(true);
    };

    const addToCartDirectly = (item: FoodItem) => {
        const newItem: CartItem = {
            ...item,
            cartId: Math.random().toString(36).substr(2, 9),
            qty: 1,
            selectedAddOns: [],
            selectedToppings: [],
            selectedOtherAddOns: [],
            finalPrice: item.price
        };

        setCart(prev => {
            const existingIndex = prev.findIndex(c => isSameItem(c, newItem));
            if (existingIndex !== -1) {
                const newCart = [...prev];
                newCart[existingIndex] = { ...newCart[existingIndex], qty: newCart[existingIndex].qty + 1 };
                return newCart;
            } else {
                return [...prev, newItem];
            }
        });
    };

    const handleConfirmCustomize = () => {
        if (!selectedItem) return;

        let variant = undefined;
        let basePrice = selectedItem.price;

        if (variantType && selectedVariantId) {
            const variants = getVariants(selectedItem, variantType);
            const found = variants.find(v => v._id === selectedVariantId);
            if (found) {
                variant = { ...found, type: variantType };
                basePrice = found.final_price || found.add_price || selectedItem.price;
            }
        }

        const addOns = (selectedItem.add_ons || []).filter(a => selectedAddOnIds.includes(a._id));
        const toppings = (selectedItem.toppings || []).filter(t => selectedToppingIds.includes(t._id));

        let otherAddOns: AddOn[] = [];
        (selectedItem.other_add_ons || []).forEach(group => {
            group.options.forEach(opt => {
                if (selectedOtherAddOnIds.includes(opt._id)) {
                    otherAddOns.push(opt);
                }
            });
        });

        const addOnsPrice = addOns.reduce((sum, a) => sum + (a.additional_price || 0), 0);
        const toppingsPrice = toppings.reduce((sum, t) => sum + (t.additional_price || 0), 0);
        const otherAddOnsPrice = otherAddOns.reduce((sum, o) => sum + (o.additional_price || 0), 0);

        const newItem: CartItem = {
            ...selectedItem,
            cartId: Math.random().toString(36).substr(2, 9),
            qty: 1,
            selectedVariant: variant as any,
            selectedAddOns: addOns,
            selectedToppings: toppings,
            selectedOtherAddOns: otherAddOns,
            finalPrice: basePrice + addOnsPrice + toppingsPrice + otherAddOnsPrice
        };

        setCart(prev => {
            const existingIndex = prev.findIndex(c => isSameItem(c, newItem));
            if (existingIndex !== -1) {
                const newCart = [...prev];
                newCart[existingIndex] = { ...newCart[existingIndex], qty: newCart[existingIndex].qty + 1 };
                return newCart;
            } else {
                return [...prev, newItem];
            }
        });

        setIsModalOpen(false);
        Toast.success('Added to cart');
    };

    const updateQuantity = (cartId: string, delta: number) => {
        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) => prev.filter((item) => item.cartId !== cartId));
    };

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

        const payload = {
            restaurant_id: userInfo?.restaurant_id?._id,
            cart_items: cart.map(item => ({
                food_id: item._id,
                name: item.name,
                food_type: item.food_type,
                no_of_quantity: item.qty,
                price: item.selectedVariant ? (item.selectedVariant.final_price || item.selectedVariant.add_price || item.price) : item.price,
                size: item.selectedVariant?.type === 'size' ? {
                    _id: item.selectedVariant._id,
                    name: item.selectedVariant.title,
                    price: item.selectedVariant.final_price
                } : null,
                quantity: item.selectedVariant?.type === 'quantity' ? {
                    _id: item.selectedVariant._id,
                    name: item.selectedVariant.title,
                    price: item.selectedVariant.final_price
                } : null,
                pieces: item.selectedVariant?.type === 'pieces' ? {
                    _id: item.selectedVariant._id,
                    name: item.selectedVariant.title,
                    price: item.selectedVariant.final_price
                } : null,
                add_ons: [
                    ...item.selectedAddOns.map(addon => ({
                        _id: addon._id,
                        name: addon.title,
                        price: addon.additional_price
                    })),
                    ...item.selectedOtherAddOns.map(addon => ({
                        _id: addon._id,
                        name: addon.title,
                        price: addon.additional_price
                    }))
                ],
                make_your_own: [],
                toppings: item.selectedToppings.map(topping => ({
                    _id: topping._id,
                    name: topping.title,
                    price: topping.additional_price
                })),
            })),
            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('+', '')
            },
            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',
        };

        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({ 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);
        }
    };

    // 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 discountAmount = discountType === 'percentage' ? (subTotal * discountValue) / 100 : discountValue;
    const tax = (subTotal - discountAmount) * (taxPercentage / 100);
    // const salesCommissionAmount = (subTotal - discountAmount) * (salesCommissionPercentage / 100);
    const salesCommissionAmount = 0;
    const total = Math.max(0, subTotal - discountAmount + tax + salesCommissionAmount);

    // Calculate current modal price
    const getCurrentModalPrice = () => {
        if (!selectedItem) return 0;
        let price = selectedItem.price;

        if (variantType && selectedVariantId) {
            const variants = getVariants(selectedItem, variantType);
            const found = variants.find(v => v._id === selectedVariantId);
            if (found) price = found.final_price || found.add_price || selectedItem.price;
        }

        const addOnsPrice = (selectedItem.add_ons || [])
            .filter(a => selectedAddOnIds.includes(a._id))
            .reduce((sum, a) => sum + (a.additional_price || 0), 0);

        const toppingsPrice = (selectedItem.toppings || [])
            .filter(t => selectedToppingIds.includes(t._id))
            .reduce((sum, t) => sum + (t.additional_price || 0), 0);

        let otherAddOnsPrice = 0;
        (selectedItem.other_add_ons || []).forEach(group => {
            group.options.forEach(opt => {
                if (selectedOtherAddOnIds.includes(opt._id)) {
                    otherAddOnsPrice += opt.additional_price || 0;
                }
            });
        });

        return price + addOnsPrice + toppingsPrice + otherAddOnsPrice;
    };

    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'}`}
                    >
                        Menu
                    </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 sm:flex-row sm:items-center">
                        <Select
                            value={selectedCategory}
                            onValueChange={(val) => {
                                setSelectedCategory(val);
                                fetchFoodItems(val);
                            }}
                        >
                            <SelectTrigger className="w-full bg-gray-50 sm:w-[200px]">
                                <SelectValue placeholder="All Categories" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="All Categories">All Categories</SelectItem>
                                {categoriesList.map((cat) => (
                                    <SelectItem key={cat.id} value={cat.id}>
                                        {cat.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>

                        <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) => (
                            <div key={item._id} className="flex h-36 w-full overflow-hidden rounded-xl border bg-white shadow-sm transition hover:shadow-md">
                                {/* Image Section */}
                                <div className="relative h-full w-32 shrink-0 bg-gray-100">
                                    <img
                                        src={item.image?.[0] ? `${BUCKET_ROOT}${item.image[0]}` : '/default-food.png'}
                                        alt={item.name}
                                        className="h-full w-full object-cover"
                                        onError={(e) => { (e.target as any).src = 'https://placehold.co/400x400?text=' + item.name }}
                                    />
                                    <div className="absolute left-2 top-2 rounded-md bg-white p-1 shadow-sm">
                                        <div className={`h-3 w-3 rounded-full ${item.food_type === 'veg' ? 'bg-green-500' : 'bg-red-500'}`} />
                                    </div>
                                </div>

                                {/* Content Section */}
                                <div className="flex flex-1 flex-col justify-between p-3 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-2 leading-tight h-6 overflow-hidden" dangerouslySetInnerHTML={{ __html: item.description || '' }} />
                                    </div>

                                    <div className="flex items-center justify-between gap-2 mt-auto">
                                        <span className="text-base font-black text-[var(--orange-500)] whitespace-nowrap">{currency}{item.price}</span>

                                        <div className="flex items-center rounded-lg bg-gray-100 p-0.5 shrink-0 border border-gray-200">
                                            {(() => {
                                                const cartItemsForId = cart.filter((c) => c._id === item._id);
                                                const totalQty = cartItemsForId.reduce((acc, c) => acc + c.qty, 0);

                                                if (totalQty > 0) {
                                                    return (
                                                        <div className="flex items-center">
                                                            <button
                                                                className="text-gray-500 hover:text-[var(--orange-500)] p-1 transition-colors"
                                                                onClick={() => {
                                                                    const lastItem = cartItemsForId[cartItemsForId.length - 1];
                                                                    if (lastItem) {
                                                                        if (lastItem.qty > 1) {
                                                                            updateQuantity(lastItem.cartId, -1);
                                                                        } else {
                                                                            removeFromCart(lastItem.cartId);
                                                                        }
                                                                    }
                                                                }}
                                                            >
                                                                <Minus size={12} />
                                                            </button>
                                                            <span className="text-xs font-black min-w-[20px] text-center text-gray-800">{totalQty}</span>
                                                            <button
                                                                className="text-gray-500 hover:text-[var(--orange-500)] p-1 transition-colors"
                                                                onClick={() => handleItemClick(item)}
                                                            >
                                                                <Plus size={12} />
                                                            </button>
                                                        </div>
                                                    );
                                                } else {
                                                    return (
                                                        <button
                                                            className="text-gray-500 hover:text-[var(--orange-500)] p-1 transition-colors"
                                                            onClick={() => handleItemClick(item)}
                                                        >
                                                            <Plus size={16} />
                                                        </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>
                        )}
                    </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({
                                    name: details.name,
                                    phone: details.phone || '',
                                    email: details.email || '',
                                    gst: details.gst || '',
                                    country_code: details.country_code || '+91'
                                });
                                setIsCustomerModalOpen(true);
                            }}
                            onAddNew={() => {
                                setCustomerDetails({ name: '', phone: '', email: '', gst: '', country_code: '+91' });
                                setIsCustomerModalOpen(true);
                            }}
                            onClear={() => {
                                setCustomerDetails({ 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">
                                    <img
                                        src={item.image?.[0] ? `${BUCKET_ROOT}${item.image[0]}` : '/default-food.png'}
                                        alt={item.name}
                                        className="h-full w-full object-cover"
                                        onError={(e) => { (e.target as any).src = 'https://placehold.co/200x200?text=' + item.name }}
                                    />
                                </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-sm font-black text-gray-900 mt-0.5">{currency}{(item.finalPrice).toFixed(2)}</div>

                                    {/* Variant & Addons Display */}
                                    <div className="text-[9px] text-gray-400 mt-1 flex flex-wrap gap-1">
                                        {item.selectedVariant && <span className="bg-gray-50 px-1.5 py-0.5 rounded border border-gray-100">{item.selectedVariant.title}</span>}
                                        {item.selectedAddOns.length > 0 && (
                                            <span className="truncate">+ {item.selectedAddOns.map(a => a.title).join(', ')}</span>
                                        )}
                                    </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 gap-2 rounded-lg bg-gray-100 p-1 border">
                                    <button
                                        onClick={() => updateQuantity(item.cartId, -1)}
                                        className="rounded p-1 hover:bg-gray-200 text-gray-600 transition-colors"
                                    >
                                        <Minus size={12} />
                                    </button>
                                    <span className="text-xs font-bold w-4 text-center">{item.qty}</span>
                                    <button
                                        onClick={() => updateQuantity(item.cartId, 1)}
                                        className="rounded p-1 hover:bg-gray-200 text-gray-600 transition-colors"
                                    >
                                        <Plus size={12} />
                                    </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-3 pt-2">
                            <Button
                                className="flex-1 bg-[var(--orange-500)] text-white hover:bg-[var(--orange-500)]/90 h-12 text-sm font-bold shadow-lg shadow-[var(--orange-500)]/20"
                                onClick={handlePlaceOrder}
                                disabled={loading || cart.length === 0}
                            >
                                {loading ? 'Placing Order...' : 'Place Order'}
                            </Button>
                            <Button
                                variant="outline"
                                className="flex-1 border-gray-200 text-gray-500 hover:bg-gray-50 h-12 text-sm font-bold"
                                onClick={() => {
                                    if (cart.length > 0) {
                                        setIsClearCartModalOpen(true);
                                    }
                                }}
                            >
                                Cancel
                            </Button>
                        </div>
                    </div>
                </div>

                {/* CUSTOMIZE MODAL */}
                <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                    <DialogContent className="max-h-[90vh] overflow-hidden flex flex-col sm:max-w-[500px] p-0 rounded-3xl border-0 shadow-2xl">
                        <div className="p-6 overflow-y-auto custom-scrollbar flex-1 pb-24">
                            <DialogHeader className="mb-6">
                                <DialogTitle className="text-xl font-bold text-gray-800">
                                    Customize {selectedItem?.name}
                                </DialogTitle>
                            </DialogHeader>

                            <div className="grid gap-6">
                                {/* Variants (Size/Quantity/Pieces) */}
                                {variantType && selectedItem && getVariants(selectedItem, variantType).length > 0 && (
                                    <div className="space-y-3">
                                        <h4 className="text-sm font-bold text-[var(--orange-500)] capitalize">
                                            {variantType === 'pieces' ? 'Pieces' : variantType === 'quantity' ? 'Quantity' : variantType === 'size' ? 'Size' : variantType}
                                        </h4>
                                        <RadioGroup value={selectedVariantId} onValueChange={setSelectedVariantId} className="grid gap-2">
                                            {getVariants(selectedItem, variantType).map((v) => (
                                                <div
                                                    key={v._id}
                                                    className={`flex items-center justify-between p-4 rounded-xl border transition-all cursor-pointer ${selectedVariantId === v._id ? 'border-[var(--orange-500)] bg-white' : 'border-gray-100 bg-white hover:border-gray-200'}`}
                                                    onClick={() => setSelectedVariantId(v._id)}
                                                >
                                                    <div className="flex items-center gap-3">
                                                        <RadioGroupItem
                                                            value={v._id}
                                                            id={v._id}
                                                            className="h-5 w-5 border-gray-300 text-[var(--orange-500)] focus:ring-[var(--orange-500)]"
                                                        />
                                                        <Label htmlFor={v._id} className="font-bold text-base cursor-pointer text-[var(--orange-500)]">{v.title}</Label>
                                                    </div>
                                                    <span className="font-bold text-gray-900">{currency}{v.final_price || v.add_price}</span>
                                                </div>
                                            ))}
                                        </RadioGroup>
                                    </div>
                                )}

                                {/* Other Add-ons Groups */}
                                {selectedItem?.other_add_ons && selectedItem.other_add_ons.length > 0 && (
                                    selectedItem.other_add_ons.map((group) => (
                                        <div key={group._id} className="space-y-3">
                                            <h4 className="text-sm font-bold text-[var(--orange-500)] capitalize">{group.title}</h4>
                                            <div className="grid gap-2">
                                                {group.options.map((option) => (
                                                    <div
                                                        key={option._id}
                                                        className={`flex items-center justify-between p-4 rounded-xl border transition-all cursor-pointer ${selectedOtherAddOnIds.includes(option._id) ? 'border-[var(--orange-500)] bg-white' : 'border-gray-100 bg-white hover:border-gray-200'}`}
                                                        onClick={() => {
                                                            const isSelected = selectedOtherAddOnIds.includes(option._id);
                                                            if (isSelected) {
                                                                setSelectedOtherAddOnIds(prev => prev.filter(id => id !== option._id));
                                                            } else {
                                                                setSelectedOtherAddOnIds(prev => [...prev, option._id]);
                                                            }
                                                        }}
                                                    >
                                                        <div className="flex items-center gap-3">
                                                            <Checkbox
                                                                checked={selectedOtherAddOnIds.includes(option._id)}
                                                                id={option._id}
                                                                className="h-5 w-5 rounded border-gray-300 text-[var(--orange-500)] focus:ring-[var(--orange-500)]"
                                                            />
                                                            <Label className="text-base font-bold cursor-pointer text-[var(--orange-500)]">{option.title}</Label>
                                                        </div>
                                                        <span className="font-bold text-gray-900">+{currency}{option.additional_price}</span>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    ))
                                )}

                                {/* Standard Add-ons */}
                                {selectedItem?.add_ons && selectedItem.add_ons.length > 0 && (
                                    <div className="space-y-3">
                                        <h4 className="text-sm font-bold text-[var(--orange-500)] capitalize">Add-ons</h4>
                                        <div className="grid gap-2">
                                            {selectedItem.add_ons.map((addon) => (
                                                <div
                                                    key={addon._id}
                                                    className={`flex items-center justify-between p-4 rounded-xl border transition-all cursor-pointer ${selectedAddOnIds.includes(addon._id) ? 'border-[var(--orange-500)] bg-white' : 'border-gray-100 bg-white hover:border-gray-200'}`}
                                                    onClick={() => {
                                                        const isSelected = selectedAddOnIds.includes(addon._id);
                                                        if (isSelected) {
                                                            setSelectedAddOnIds(prev => prev.filter(id => id !== addon._id));
                                                        } else {
                                                            setSelectedAddOnIds(prev => [...prev, addon._id]);
                                                        }
                                                    }}
                                                >
                                                    <div className="flex items-center gap-3">
                                                        <Checkbox
                                                            checked={selectedAddOnIds.includes(addon._id)}
                                                            id={addon._id}
                                                            className="h-5 w-5 rounded border-gray-300 text-[var(--orange-500)] focus:ring-[var(--orange-500)]"
                                                        />
                                                        <Label className="text-base font-bold cursor-pointer text-[var(--orange-500)]">{addon.title} {addon.customer_selection === 'compulsory' && <span className="text-red-500">*</span>}</Label>
                                                    </div>
                                                    <span className="font-bold text-gray-900">+{currency}{addon.additional_price}</span>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {/* Toppings */}
                                {selectedItem?.toppings && selectedItem.toppings.length > 0 && (
                                    <div className="space-y-3">
                                        <h4 className="text-sm font-bold text-[var(--orange-500)] capitalize">Toppings</h4>
                                        <div className="grid gap-2">
                                            {selectedItem.toppings.map((topping) => (
                                                <div
                                                    key={topping._id}
                                                    className={`flex items-center justify-between p-4 rounded-xl border transition-all cursor-pointer ${selectedToppingIds.includes(topping._id) ? 'border-[var(--orange-500)] bg-white' : 'border-gray-100 bg-white hover:border-gray-200'}`}
                                                    onClick={() => {
                                                        const isSelected = selectedToppingIds.includes(topping._id);
                                                        if (isSelected) {
                                                            setSelectedToppingIds(prev => prev.filter(id => id !== topping._id));
                                                        } else {
                                                            setSelectedToppingIds(prev => [...prev, topping._id]);
                                                        }
                                                    }}
                                                >
                                                    <div className="flex items-center gap-3">
                                                        <Checkbox
                                                            checked={selectedToppingIds.includes(topping._id)}
                                                            id={topping._id}
                                                            className="h-5 w-5 rounded border-gray-300 text-[var(--orange-500)] focus:ring-[var(--orange-500)]"
                                                        />
                                                        <Label className="text-base font-bold cursor-pointer text-[var(--orange-500)]">{topping.title}</Label>
                                                    </div>
                                                    <span className="font-bold text-gray-900">+{currency}{topping.additional_price}</span>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>

                        <div className="p-6 bg-white border-t flex items-center justify-between rounded-b-3xl">
                            <div className="flex items-center gap-1">
                                <span className="text-lg font-bold text-[var(--orange-500)]">Total:</span>
                                <span className="text-lg font-bold text-[var(--orange-500)]">{currency}{getCurrentModalPrice().toFixed(2)}</span>
                            </div>
                            <Button
                                onClick={handleConfirmCustomize}
                                className="bg-[var(--orange-500)] text-white hover:bg-[var(--orange-500)]/90 h-10 px-6 rounded-lg text-sm font-bold transition-all active:scale-95"
                            >
                                Add Item
                            </Button>
                        </div>
                    </DialogContent>
                </Dialog>
            </div>

            {/* DISCOUNT MODAL */}
            <Dialog open={isDiscountModalOpen} onOpenChange={setIsDiscountModalOpen}>
                <DialogContent className="sm:max-w-[400px] rounded-3xl border-0 shadow-2xl p-8">
                    <DialogHeader className="mb-6">
                        <DialogTitle className="text-2xl font-black text-gray-800">Manage Discount</DialogTitle>
                    </DialogHeader>
                    <div className="grid gap-6">
                        <div className="space-y-3">
                            <Label className="text-xs font-black uppercase text-gray-400 tracking-widest">Discount Type</Label>
                            <RadioGroup
                                value={tempDiscountType}
                                onValueChange={(val: 'percentage' | 'fixed') => setTempDiscountType(val)}
                                className="flex gap-4"
                            >
                                <div className={`flex items-center justify-center p-3 rounded-xl border-2 flex-1 cursor-pointer transition-all ${tempDiscountType === 'percentage' ? 'border-[var(--orange-500)] bg-[var(--orange-50)] shadow-sm' : 'border-gray-50 bg-gray-50'}`} onClick={() => setTempDiscountType('percentage')}>
                                    <RadioGroupItem value="percentage" id="percentage" className="sr-only" />
                                    <Label htmlFor="percentage" className="font-bold cursor-pointer">Percentage (%)</Label>
                                </div>
                                <div className={`flex items-center justify-center p-3 rounded-xl border-2 flex-1 cursor-pointer transition-all ${tempDiscountType === 'fixed' ? 'border-[var(--orange-500)] bg-[var(--orange-50)] shadow-sm' : 'border-gray-50 bg-gray-50'}`} onClick={() => setTempDiscountType('fixed')}>
                                    <RadioGroupItem value="fixed" id="fixed" className="sr-only" />
                                    <Label htmlFor="fixed" className="font-bold cursor-pointer">Fixed</Label>
                                </div>
                            </RadioGroup>
                        </div>
                        <div className="space-y-3">
                            <Label className="text-xs font-black uppercase text-gray-400 tracking-widest">Discount Value</Label>
                            <div className="relative">
                                <span className="absolute left-4 top-1/2 -translate-y-1/2 font-black text-gray-400">{tempDiscountType === 'percentage' ? '%' : currency}</span>
                                <Input
                                    type="number"
                                    min="0"
                                    className="h-14 pl-10 text-xl font-black bg-gray-50 border-0 focus-visible:ring-2 focus-visible:ring-[var(--orange-500)] rounded-2xl"
                                    value={tempDiscountValue === 0 ? '' : tempDiscountValue}
                                    onChange={(e) => {
                                        const val = e.target.value;
                                        if (Number(val) < 0) return;
                                        setTempDiscountValue(val === '' ? 0 : Number(val));
                                    }}
                                    placeholder="0.00"
                                />
                            </div>
                        </div>
                    </div>
                    <DialogFooter className="mt-8 flex gap-3">
                        <Button variant="ghost" className="flex-1 font-bold h-12 rounded-2xl" onClick={() => setIsDiscountModalOpen(false)}>Cancel</Button>
                        <Button
                            className="flex-1 bg-[var(--orange-500)] text-white hover:bg-[var(--orange-500)]/90 font-bold h-12 rounded-2xl shadow-lg shadow-[var(--orange-500)]/20"
                            onClick={() => {
                                setDiscountType(tempDiscountType);
                                setDiscountValue(tempDiscountValue);
                                setIsDiscountModalOpen(false);
                                Toast.success('Discount applied');
                            }}
                        >
                            Apply Discount
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* TAX MODAL */}
            <Dialog open={isTaxModalOpen} onOpenChange={setIsTaxModalOpen}>
                <DialogContent className="sm:max-w-[400px] rounded-3xl border-0 shadow-2xl p-8">
                    <DialogHeader className="mb-6">
                        <DialogTitle className="text-2xl font-black text-gray-800">Manage Tax</DialogTitle>
                    </DialogHeader>
                    <div className="grid gap-6">
                        <div className="space-y-3">
                            <Label className="text-xs font-black uppercase text-gray-400 tracking-widest">Tax Percentage</Label>
                            <div className="relative">
                                <span className="absolute left-4 top-1/2 -translate-y-1/2 font-black text-gray-400">%</span>
                                <Input
                                    type="number"
                                    min="0"
                                    max="100"
                                    className="h-14 pl-10 text-xl font-black bg-gray-50 border-0 focus-visible:ring-2 focus-visible:ring-[var(--orange-500)] rounded-2xl"
                                    value={tempTaxPercentage === 0 ? '' : tempTaxPercentage}
                                    onChange={(e) => {
                                        const val = e.target.value;
                                        if (Number(val) < 0 || Number(val) > 100) return;
                                        setTempTaxPercentage(val === '' ? 0 : Number(val));
                                    }}
                                    placeholder="0.00"
                                />
                            </div>
                        </div>
                    </div>
                    <DialogFooter className="mt-8 flex gap-3">
                        <Button variant="ghost" className="flex-1 font-bold h-12 rounded-2xl" onClick={() => setIsTaxModalOpen(false)}>Cancel</Button>
                        <Button
                            className="flex-1 bg-[var(--orange-500)] text-white hover:bg-[var(--orange-500)]/90 font-bold h-12 rounded-2xl shadow-lg shadow-[var(--orange-500)]/20"
                            onClick={() => {
                                setCustomTaxPercentage(tempTaxPercentage);
                                setIsTaxModalOpen(false);
                                Toast.success('Tax applied');
                            }}
                        >
                            Apply Tax
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* CUSTOMER MODAL */}
            <CustomerModal
                isOpen={isCustomerModalOpen}
                onClose={() => setIsCustomerModalOpen(false)}
                onSave={(details) => {
                    setCustomerDetails({
                        name: details.name,
                        phone: details.phone || '',
                        email: details.email || '',
                        gst: details.gst || '',
                        country_code: details.country_code || '+91'
                    });
                }}
                initialData={customerDetails}
            />
            <DeleteDialog
                isOpen={isClearCartModalOpen}
                onClose={() => setIsClearCartModalOpen(false)}
                handleDelete={() => {
                    setCart([]);
                    setIsClearCartModalOpen(false);
                    Toast.success('Cart cleared');
                }}
                title="Clear Cart"
                description="Are you sure you want to remove all items from the cart?"
                actionButtonText="Yes, Clear Cart"
            />
        </DashboardLayout>
    );
}
