"use client";
import React, { useState, useEffect, useMemo, useCallback } from "react";
import type { CarouselApi } from "@/components/ui/carousel";

import { Container } from "@/components/ui/container";
import { Button } from "@/components/ui/button";
import { TypographyH3 } from "@/components/ui/typography";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Carousel, CarouselContent, CarouselItem } from "@/components/ui/carousel";
import ProductCard from "./ProductCard";
import { ChevronLeft, ChevronRight } from "lucide-react";
import type { Product } from "@/types/product";
import { useProducts } from "@/hooks/useProducts";
import { useCategories } from "@/hooks/useCategories";
import { convertApiProductToProduct } from "@/types/api";

const getBadgeVariant = (count: number): "dark" | "lime" | "red" | "gray" | "yellow" => {
    if (count >= 100) return "lime";
    if (count >= 50) return "dark";
    if (count >= 20) return "yellow";
    if (count >= 10) return "red";
    return "gray";
};

// Memoized ProductCard wrapper to prevent unnecessary re-renders
const MemoizedProductCard = React.memo(ProductCard);

const FeaturedItems: React.FC = () => {
    const [favorites, setFavorites] = useState<Record<string, boolean>>({});
    const [selectedCategoryId, setSelectedCategoryId] = useState<number | undefined>();
    const [api, setApi] = useState<CarouselApi | null>(null);
    const [canScrollPrev, setCanScrollPrev] = useState(false);
    const [canScrollNext, setCanScrollNext] = useState(true);
    
    // Fetch categories and products from API
    const { categories, loading: categoriesLoading } = useCategories();
    const { products: apiProducts, loading: productsLoading } = useProducts({
        category_id: selectedCategoryId,
    });

    // Memoize expensive computations
    const products = useMemo(() => 
        apiProducts.map(convertApiProductToProduct),
        [apiProducts]
    );

    // Get leaf categories (those with children) for the tabs
    const leafCategories = useMemo(() => {
        return categories
            .filter(cat => cat.children && cat.children.length > 0)
            .flatMap(cat => cat.children || []);
    }, [categories]);

    // Memoize product slices to prevent recalculation
    const { topProducts, bottomProducts } = useMemo(() => ({
        topProducts: products.slice(0, 6),
        bottomProducts: products.slice(6, 9)
    }), [products]);

    // Optimize toggle favorite function with useCallback
    const toggleFav = useCallback((id: string) => {
        setFavorites((prev) => ({ ...prev, [id]: !prev[id] }));
    }, []);

    // Set initial category - only run when categories change
    useEffect(() => {
        if (leafCategories.length > 0 && selectedCategoryId === undefined) {
            setSelectedCategoryId(leafCategories[0].id);
        }
    }, [leafCategories, selectedCategoryId]);

    // Carousel API setup - optimized with useCallback
    const handleCarouselSelect = useCallback(() => {
        if (!api) return;
        setCanScrollPrev(api.canScrollPrev());
        setCanScrollNext(api.canScrollNext());
    }, [api]);

    useEffect(() => {
        if (!api) return;
        
        api.on('select', handleCarouselSelect);
        api.on('reInit', handleCarouselSelect);
        handleCarouselSelect();
        
        return () => {
            api.off('select', handleCarouselSelect);
        };
    }, [api, handleCarouselSelect]);

    // Load favorites from localStorage only once
    useEffect(() => {
        try {
            const raw = localStorage.getItem("featured_favorites");
            if (raw) setFavorites(JSON.parse(raw));
        } catch (error) {
            console.warn('Failed to load favorites from localStorage:', error);
        }
    }, []);

    // Save favorites to localStorage - debounced
    useEffect(() => {
        const timer = setTimeout(() => {
            try {
                localStorage.setItem("featured_favorites", JSON.stringify(favorites));
            } catch (error) {
                console.warn('Failed to save favorites to localStorage:', error);
            }
        }, 300);

        return () => clearTimeout(timer);
    }, [favorites]);

    // Optimize carousel navigation functions
    const scrollPrev = useCallback(() => api?.scrollPrev(), [api]);
    const scrollNext = useCallback(() => api?.scrollNext(), [api]);
    
    // Show loading state with simplified skeleton
    if (categoriesLoading || productsLoading) {
        return (
            <section className="py-12 px-4 md:px-6">
                <Container>
                    <div className="animate-pulse">
                        <div className="h-12 bg-gray-200 rounded w-1/3 mb-8"></div>
                        <div className="grid grid-cols-1 lg:grid-cols-[270px_1fr] gap-7">
                            <div className="space-y-2">
                                {Array.from({ length: 4 }).map((_, i) => (
                                    <div key={i} className="h-16 bg-gray-200 rounded"></div>
                                ))}
                            </div>
                            <div className="grid grid-cols-2 sm:grid-cols-2 gap-6">
                                {Array.from({ length: 4 }).map((_, i) => (
                                    <div key={i} className="space-y-4">
                                        <div className="aspect-square bg-gray-200 rounded"></div>
                                        <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                                        <div className="h-4 bg-gray-200 rounded w-1/2"></div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </Container>
            </section>
        );
    }

    return (
        <section className="py-12 px-2 md:px-6">
            <Container className="">
                <div className="flex items-start sm:items-center sm:flex-row flex-col justify-between gap-4 mb-6 lg:mb-[46px]">
                    <TypographyH3 className="text-[36px] sm:text-[47px] leading-10 sm:leading-[59px] font-bold prompt tracking-[-0.94px] text-black">
                        أبرز <span className="text-[#F5411C]">المنتجات</span>
                    </TypographyH3>
                    <div className="w-full sm:w-fit flex items-end justify-end sm:items-center gap-4 sm:gap-6">
                        <Button
                            variant="outline"
                            size="icon"
                            className="w-10 sm:w-[55px] h-10 sm:h-[55px] rounded-full border-black hover:bg-black hover:text-white transition-colors"
                            onClick={scrollNext}
                            disabled={!canScrollNext}
                        >
                            <ChevronRight className="size-6" />
                        </Button>
                        <Button
                            variant="outline"
                            size="icon"
                            className="w-10 sm:w-[55px] h-10 sm:h-[55px] rounded-full border-black hover:bg-black hover:text-white transition-colors"
                            onClick={scrollPrev}
                            disabled={!canScrollPrev}
                        >
                            <ChevronLeft className="size-6" />
                        </Button>
                    
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-[270px_1fr] gap-7 overflow-hidden">
                    {/* Tabs */}
                    <div className="max-h-[500px] overflow-y-auto overflow-x-hidden">
                        <Tabs value={selectedCategoryId?.toString()} onValueChange={(val) => setSelectedCategoryId(Number(val))} className="w-full rounded-none px-0!">
                            <TabsList className="flex flex-col items-start rounded-none w-full h-auto bg-transparent p-0! gap-0!">
                                {leafCategories.map((c) => (
                                    <TabsTrigger
                                        key={c.id}
                                        value={c.id.toString()}
                                        className="justify-start pl-6! pr-0! py-[15px]! gap-4.5 rounded-none border-l-2 border-l-[#E2E2E2] data-[state=active]:border-l-[#F5411C] data-[state=active]:bg-transparent w-[270px] data-[state=active]:min-w-[270px]! data-[state=active]:text-[#2C2C2C] hover:bg-gray-50 transition-colors flex-nowrap"
                                        >
                                        <TypographyH3 className="text-[16px] leading-[21px] font-medium text-[#2C2C2C] truncate">{c.name}</TypographyH3>
                                        <Badge 
                                            variant={getBadgeVariant(apiProducts.length)}
                                            size="default"
                                            className="font-bold border-none w-10"
                                            count={apiProducts.length}
                                        />
                                    </TabsTrigger>
                                ))}
                            </TabsList>
                        </Tabs>
                    </div>

                    {/* Slider Section */}
                    <div className="w-full overflow-hidden">
                        <Carousel 
                            className="w-full" 
                            setApi={setApi}
                            opts={{
                                align: "start",
                                containScroll: false,
                                dragFree: true,
                                skipSnaps: false,
                                duration: 20, // Faster animation
                            }}
                        >
                            <CarouselContent className="-ml-6">
                                {topProducts.map((p: Product) => (
                                    <CarouselItem key={p.id} className="pl-6 sm:pl-7 basis-full sm:basis-1/2 lg:basis-[42%]">
                                        <div className="p-1">
                                            <MemoizedProductCard
                                                id={p.id}
                                                slug={p.slug}
                                                title={p.title}
                                                price={p.price}
                                                imageSrc={p.imageSrc}
                                                rating={p.rating || 4.5}
                                                ratingCount={p.ratingCount || 100}
                                                variant="featured"
                                                isFavorite={!!favorites[p.id]}
                                                onToggleFavorite={() => toggleFav(p.id)}
                                            />
                                        </div>
                                    </CarouselItem>
                                ))}
                            </CarouselContent>
                        </Carousel>
                    </div>
                </div>

                {/* Bottom Products */}
                <div className="mt-12 lg:mt-20">
                    <div className="w-full grid grid-cols-2 sm:grid-cols-2 xl:grid-cols-3 gap-[42px]">
                        {bottomProducts.map((p: Product) => (
                            <Card key={p.id} className="group border-none shadow-none">
                                <CardContent className="p-0">
                                    <MemoizedProductCard
                                        id={p.id}
                                        slug={p.slug}
                                        title={p.title}
                                        price={p.price}
                                        imageSrc={p.imageSrc}
                                        rating={p.rating || 4.5}
                                        ratingCount={p.ratingCount || 100}
                                        variant="featured"
                                        isFavorite={!!favorites[p.id]}
                                        onToggleFavorite={() => toggleFav(p.id)}
                                    />
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                </div>
            </Container>
        </section>
    );
};

export default FeaturedItems;