"use client";

import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import DashboardLayout from '@/components/layout/DashboardLayout';
import { ChevronLeft } from 'lucide-react';
import CartSidebar, { CartItem } from '@/components/grocery/CartSidebar';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { logEvent } from '@/utils/analytics';

import { currency, getValidImage } from '@/lib/utils';
import ProductCard from '@/components/grocery/ProductCard';
import { Modal } from '@/components/ui/modal';
import { Button } from '@/components/ui/button';

const CategoryPage = () => {
    const { slug } = useParams();
    const router = useRouter();
    const searchParams = useSearchParams();
    const restaurantIdFromQuery = searchParams.get('restaurantId');
    const orange = "hsl(var(--brand-500))";
    const [cartItems, setCartItems] = useState<CartItem[]>([]);
    const [isCartOpen, setIsCartOpen] = useState(false);
    const { Toast } = useGlobalContext();

    const [products, setProducts] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [categoryName, setCategoryName] = useState("");
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isFetching, setIsFetching] = useState(false);

    const [isInitialized, setIsInitialized] = useState(false);
    const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
    const [pendingProduct, setPendingProduct] = useState<any>(null);
    const observerTarget = useRef(null);

    useEffect(() => {
        const savedCart = localStorage.getItem('groceryCartItems');
        if (savedCart) {
            setCartItems(JSON.parse(savedCart));
        }
        setIsInitialized(true);

        const handleToggle = () => setIsCartOpen(prev => !prev);
        window.addEventListener('toggle-grocery-cart', handleToggle);
        return () => window.removeEventListener('toggle-grocery-cart', handleToggle);
    }, []);

    useEffect(() => {
        if (!isInitialized) return;
        localStorage.setItem('groceryCartItems', JSON.stringify(cartItems));
        window.dispatchEvent(new CustomEvent('grocery-cart-updated', { detail: cartItems.length }));
    }, [cartItems, isInitialized]);

    const fetchProducts = async (pageNumber: number) => {
        if (!slug) return;
        try {
            if (pageNumber === 1) setLoading(true);
            setIsFetching(true);

            const query = `category=${slug}&page=${pageNumber}&limit=10${restaurantIdFromQuery ? `&store_id=${restaurantIdFromQuery}` : ''}`;
            const response = await apis.Grocery.getByCategory(query);

            if (response?.data) {
                const newData = response.data;
                setProducts(prev => {
                    if (pageNumber === 1) return newData;
                    const existingIds = new Set(prev.map((p: any) => p._id));
                    const uniqueNewItems = newData.filter((p: any) => !existingIds.has(p._id));
                    return [...prev, ...uniqueNewItems];
                });

                if (newData.length > 0 && pageNumber === 1) {
                    setCategoryName(newData[0]?.category?.category_name || slug as string);
                }

                // Check if we have more pages
                if (newData.length < 10 || (response.total && (pageNumber * 10) >= response.total)) {
                    setHasMore(false);
                } else {
                    setHasMore(true);
                }
            }
        } catch (error) {
            Toast.error(error);
        } finally {
            setLoading(false);
            setIsFetching(false);
        }
    };

    useEffect(() => {
        setPage(1);
        setProducts([]);
        setHasMore(true);
        fetchProducts(1);
    }, [slug]);

    useEffect(() => {
        if (page > 1) {
            fetchProducts(page);
        }
    }, [page]);

    useEffect(() => {
        const observer = new IntersectionObserver(
            entries => {
                if (entries[0].isIntersecting && hasMore && !isFetching) {
                    setPage(prev => prev + 1);
                }
            },
            { threshold: 0.1 }
        );

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

        return () => {
            if (observerTarget.current) {
                observer.unobserve(observerTarget.current);
            }
        };
    }, [hasMore, isFetching]);

    const addToCart = useCallback((product: any) => {
        const productId = product._id || product.id;
        const productRestaurantId = product.restaurant_id || product.restaurantId || product.restaurant?._id || restaurantIdFromQuery;

        const currentCartRestaurantId = cartItems.length > 0 ? String(cartItems[0].restaurantId) : undefined;
        const targetRestaurantId = productRestaurantId ? String(productRestaurantId) : undefined;

        if (currentCartRestaurantId && targetRestaurantId && currentCartRestaurantId !== targetRestaurantId) {
            setPendingProduct({ ...product, restaurant_id: targetRestaurantId });
            setIsConfirmModalOpen(true);
            return;
        }

        const hasDiscount = (product.is_discount_active !== false) &&
            product.discounted_price !== undefined &&
            product.discounted_price !== null &&
            Number(product.discounted_price) > 0 &&
            Number(product.discounted_price) < Number(product.price);

        const effectivePrice = hasDiscount ? Number(product.discounted_price) : Number(product.price || product.base_price || product.original_price || 0);

        logEvent("add_to_cart", {
            currency: "INR",
            value: effectivePrice,
            items: [{
                item_id: productId,
                item_name: product.name || product.title,
                price: effectivePrice,
                quantity: 1,
                item_category: "grocery"
            }]
        });

        setCartItems(prev => {
            const existing = prev.find(item => item.id === productId);
            if (existing) {
                return prev.map(item =>
                    item.id === productId ? { ...item, quantity: item.quantity + 1 } : item
                );
            }

            if (product.weight && typeof product.price === 'string' && product.price.includes(currency)) {
                return [...prev, { ...product, id: productId, quantity: 1, restaurantId: targetRestaurantId }];
            }
            return [...prev, {
                id: productId,
                name: product.name,
                weight: `${product.quantity || ''} ${product.unit || ''}`.trim(),
                price: `${currency}${effectivePrice}.00`,
                originalPrice: hasDiscount ? `${currency}${product.price}.00` : undefined,
                image: getValidImage(product.imageUrl),
                quantity: 1,
                restaurantId: targetRestaurantId,
                totalStock: product.total_stock
            }];
        });
    }, [cartItems, restaurantIdFromQuery]);

    const handleConfirmClearCart = () => {
        if (pendingProduct) {
            const productId = pendingProduct._id || pendingProduct.id;
            const productRestaurantId = pendingProduct.restaurant_id || pendingProduct.restaurantId || pendingProduct.restaurant?._id || restaurantIdFromQuery;
            const targetRestaurantId = productRestaurantId ? String(productRestaurantId) : undefined;

            const hasDiscount = (pendingProduct.is_discount_active !== false) &&
                pendingProduct.discounted_price !== undefined &&
                pendingProduct.discounted_price !== null &&
                Number(pendingProduct.discounted_price) > 0 &&
                Number(pendingProduct.discounted_price) < Number(pendingProduct.price);

            const effectivePrice = hasDiscount ? Number(pendingProduct.discounted_price) : Number(pendingProduct.price || pendingProduct.base_price || pendingProduct.original_price || 0);

            if (pendingProduct.weight && typeof pendingProduct.price === 'string' && pendingProduct.price.includes(currency)) {
                setCartItems([{ ...pendingProduct, id: productId, quantity: 1, restaurantId: targetRestaurantId }]);
            } else {
                setCartItems([{
                    id: productId,
                    name: pendingProduct.name,
                    weight: `${pendingProduct.quantity || ''} ${pendingProduct.unit || ''}`.trim(),
                    price: `${currency}${effectivePrice}.00`,
                    originalPrice: hasDiscount ? `${currency}${pendingProduct.price}.00` : undefined,
                    image: getValidImage(pendingProduct.imageUrl),
                    quantity: 1,
                    restaurantId: targetRestaurantId,
                    totalStock: pendingProduct.total_stock
                }]);
            }
            setPendingProduct(null);
        }
        setIsConfirmModalOpen(false);
    };

    const removeFromCart = useCallback((productId: string | number) => {
        setCartItems(prev => {
            const existing = prev.find(item => item.id === productId);
            if (existing && existing.quantity > 1) {
                return prev.map(item =>
                    item.id === productId ? { ...item, quantity: item.quantity - 1 } : item
                );
            }
            return prev.filter(item => item.id !== productId);
        });
    }, []);

    const deleteItem = useCallback((productId: string | number) => {
        setCartItems(prev => prev.filter(item => item.id !== productId));
    }, []);

    const cartQuantities = useMemo(() => {
        const quantities: Record<string | number, number> = {};
        cartItems.forEach(item => {
            // item.id is set to product._id when adding to cart
            quantities[item.id] = item.quantity;
        });
        return quantities;
    }, [cartItems]);

    return (
        <div className="relative overflow-x-hidden min-h-screen bg-gray-50/50">
            <div className={`max-w-7xl mx-auto px-4 py-8 space-y-8 transition-all duration-300 ${isCartOpen ? 'mr-[400px]' : ''}`}>
                {/* Header */}
                <div className="flex items-center gap-4">
                    <button
                        onClick={() => router.back()}
                        className="w-10 h-10 rounded-full bg-white shadow-sm flex items-center justify-center hover:bg-gray-50 transition-colors border border-gray-100"
                    >
                        <ChevronLeft className="w-6 h-6 text-gray-600" />
                    </button>
                    <h1 className="text-3xl font-bold text-gray-900 capitalize">
                        {categoryName || (slug as string)?.replace(/-/g, ' ')}
                    </h1>
                </div>

                {/* Products Grid */}
                {loading ? (
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
                        {Array.from({ length: 10 }).map((_, i) => (
                            <div key={i} className="aspect-[4/5] bg-gray-200 rounded-[2rem] animate-pulse" />
                        ))}
                    </div>
                ) : products.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-20 text-center animate-in fade-in zoom-in duration-500">
                        <div className="relative mb-8">
                            {/* Brand purple glow effect */}
                            <div className="absolute inset-0 bg-brand-500/10 blur-3xl rounded-full" />

                            {/* Icon Container */}
                            <div className="relative w-32 h-32 bg-white rounded-full flex items-center justify-center border-4 border-brand-100 shadow-xl shadow-brand-50">
                                <svg width="64" height="64" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M30 35H70V75C70 77.7614 67.7614 80 65 80H35C32.2386 80 30 77.7614 30 75V35Z" stroke="#000000" strokeWidth="5" strokeLinejoin="round" />
                                    <path d="M40 35V30C40 24.4772 44.4772 20 50 20C55.5228 20 60 24.4772 60 30V35" stroke="#000000" strokeWidth="5" strokeLinecap="round" />
                                    <path d="M45 55C45 55 47 62 50 62C53 62 55 55 55 55" stroke="#000000" strokeWidth="5" strokeLinecap="round" />
                                </svg>
                            </div>
                        </div>

                        <h3 className="text-3xl font-black text-gray-900 mb-3">No Items Found</h3>
                        <p className="text-gray-500 max-w-sm mx-auto mb-10 text-lg leading-relaxed">
                            We couldn't find any items matching your search or in this category. Try a different term or clear the filter.
                        </p>

                        <button
                            onClick={() => router.push('/grocery')}
                            className="px-12 py-4 bg-brand-500 text-white rounded-full font-bold shadow-2xl shadow-brand-200 hover:bg-brand-600 hover:-translate-y-1 transition-all active:scale-95 text-lg"
                        >
                            Back to Grocery
                        </button>
                    </div>
                ) : (
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
                        {products.map((product) => {
                            const productRestaurantId = product.restaurant_id || product.restaurantId || product.restaurant?._id || restaurantIdFromQuery;
                            return (
                                <ProductCard
                                    key={product._id}
                                    product={{ ...product, restaurant_id: productRestaurantId }}
                                    quantity={
                                        (cartItems.length > 0 &&
                                            String(productRestaurantId) === String(cartItems[0].restaurantId))
                                            ? (cartQuantities[product._id] || 0)
                                            : 0
                                    }
                                    onAdd={addToCart}
                                    onRemove={removeFromCart}
                                />
                            );
                        })}
                    </div>
                )}

                {isFetching && page > 1 && (
                    <div className="flex justify-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    </div>
                )}
                <div ref={observerTarget} className="h-4 w-full" />
            </div>

            <CartSidebar
                isOpen={isCartOpen}
                onClose={() => setIsCartOpen(false)}
                items={cartItems}
                onAdd={addToCart}
                onRemove={removeFromCart}
                onDeleteItem={deleteItem}
                orange={orange}
                onClearCart={() => setCartItems([])}
            />

            <Modal
                title="Replace cart item?"
                description="Your cart contains items from another store. Do you want to discard the selection and add items from this store instead?"
                isOpen={isConfirmModalOpen}
                onClose={() => setIsConfirmModalOpen(false)}
            >
                <div className="flex justify-end gap-3 mt-4">
                    <Button variant="outline" onClick={() => setIsConfirmModalOpen(false)}>
                        Cancel
                    </Button>
                    <Button
                        style={{ backgroundColor: orange }}
                        className="text-white"
                        onClick={handleConfirmClearCart}
                    >
                        OK
                    </Button>
                </div>
            </Modal>
        </div>
    );
};

export default function Category() {
    return (
        <DashboardLayout>
            <CategoryPage />
        </DashboardLayout>
    );
}
