'use client';

import { useRouter } from '@/shared/config/i18n/navigation';
import { cn } from '@/shared/lib/utils';
import { Button } from '@/shared/ui/button';
import { Card } from '@/shared/ui/card';
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  type CarouselApi,
} from '@/shared/ui/carousel';
import { Skeleton } from '@/shared/ui/skeleton';
import { ProductCard } from '@/widgets/categories/ui/product-card';
import { ProductRes } from '@/widgets/welcome/lib/api';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { memo, useEffect, useRef, useState } from 'react';

//////////////////////////
/// CategoryCarousel optimized
//////////////////////////
interface CategoryCarouselProps {
  category: ProductRes;
  isLoading: boolean;
  isError: boolean;
}

const CategoryCarousel = memo(function CategoryCarousel({
  category,
  isLoading,
  isError,
}: CategoryCarouselProps) {
  const router = useRouter();
  const [api, setApi] = useState<CarouselApi>();
  const [canScrollPrev, setCanScrollPrev] = useState(false);
  const [canScrollNext, setCanScrollNext] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  const sectionRef = useRef<HTMLElement>(null);

  // Intersection Observer
  useEffect(() => {
    if (!sectionRef.current) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setIsVisible(true);
            observer.disconnect();
          }
        });
      },
      { rootMargin: '100px', threshold: 0.1 },
    );
    observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  // Carousel buttons
  useEffect(() => {
    if (!api) return;
    const updateButtons = () => {
      setCanScrollPrev(api.canScrollPrev());
      setCanScrollNext(api.canScrollNext());
    };
    updateButtons();
    api.on('select', updateButtons);
    api.on('reInit', updateButtons);
    return () => {
      api.off('select', updateButtons);
      api.off('reInit', updateButtons);
    };
  }, [api]);

  const scrollPrev = () => api?.scrollPrev();
  const scrollNext = () => api?.scrollNext();

  if (!isVisible) {
    return (
      <section
        ref={sectionRef}
        className="relative custom-container mt-5 min-h-[300px]"
      />
    );
  }

  const activeProducts =
    category?.products?.filter((p) => p.state === 'A') ?? [];

  return (
    <section
      ref={sectionRef}
      className="relative custom-container mt-5 justify-center items-center border-b border-slate-200"
    >
      <div className="flex items-center justify-between pb-3">
        <div
          className="flex items-center gap-2 group cursor-pointer"
          onClick={() => router.push(`/category/${category.id}/`)}
        >
          <h2 className="text-2xl font-bold text-slate-800 group-hover:text-blue-600 transition-colors">
            {category.name || '---'}
          </h2>
          <div className="p-1.5 bg-slate-100 rounded-full group-hover:bg-blue-100 transition-all">
            <ChevronRight className="text-slate-600 group-hover:text-blue-600 group-hover:translate-x-0.5 transition-all" />
          </div>
        </div>
      </div>

      <Carousel
        opts={{ align: 'start', dragFree: true }}
        className="w-full mt-2"
        setApi={setApi}
      >
        <CarouselContent className="pr-[12%] sm:pr-0">
          {isLoading || isError || activeProducts.length === 0
            ? Array.from({ length: 6 }).map((__, index) => (
                <CarouselItem
                  key={index}
                  className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
                >
                  <Card className="p-3 space-y-3 rounded-xl">
                    <Skeleton className="h-40 sm:h-48 md:h-56 w-full rounded-lg" />
                    <Skeleton className="h-4 w-3/4" />
                    <Skeleton className="h-4 w-1/2" />
                    <Skeleton className="h-10 w-full rounded-lg" />
                  </Card>
                </CarouselItem>
              ))
            : activeProducts.map((product) => (
                <CarouselItem
                  key={product.id}
                  className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
                >
                  <ProductCard product={product} />
                </CarouselItem>
              ))}
        </CarouselContent>
      </Carousel>

      <Button
        onClick={scrollNext}
        className={cn(
          'absolute top-0 right-4 max-lg:hidden text-white cursor-pointer',
          canScrollNext
            ? 'bg-green-600 hover:bg-green-600/70'
            : 'bg-green-600/50 cursor-not-allowed',
        )}
        disabled={!canScrollNext}
        aria-label="next images"
        size="icon"
      >
        <ChevronRight className="size-6" />
      </Button>
      <Button
        onClick={scrollPrev}
        className={cn(
          'absolute top-0 right-16 max-lg:hidden text-white cursor-pointer',
          canScrollPrev
            ? 'bg-green-600 hover:bg-green-600/70'
            : 'bg-green-600/50 cursor-not-allowed',
        )}
        disabled={!canScrollPrev}
        size="icon"
      >
        <ChevronLeft className="size-6" />
      </Button>
    </section>
  );
});

export default CategoryCarousel;
