'use client';

import { ProductTypes } from '@/shared/config/api/category/type';
import { product_api } from '@/shared/config/api/product/api';
import { useRouter } from '@/shared/config/i18n/navigation';
import { cn } from '@/shared/lib/utils';
import { Button } from '@/shared/ui/button';
import {
  Carousel,
  CarouselApi,
  CarouselContent,
  CarouselItem,
} from '@/shared/ui/carousel';
import { useQuery } from '@tanstack/react-query';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { ProductCard } from './product-card';

export function CategoryCarousel({ category }: { category: ProductTypes }) {
  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 - faqat ko'ringan kategoriyalar uchun API so'rov yuborish
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setIsVisible(true);
            observer.disconnect(); // Bir marta ko'ringandan keyin observer ni o'chirish
          }
        });
      },
      {
        rootMargin: '100px', // Sahifa 100px yaqinlashganda yuklash
        threshold: 0.1,
      },
    );

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

    return () => observer.disconnect();
  }, []);

  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 = () => {
    if (api) {
      api?.scrollPrev();
    }
  };

  const scrollNext = () => {
    if (api) {
      api?.scrollNext();
    }
  };

  // Faqat ko'ringanda API so'rov yuborish
  const { data: product, isLoading } = useQuery({
    queryKey: ['product_list', category.id],
    queryFn: () =>
      product_api.list({
        page: 1,
        page_size: 16,
        product_type_id: category.id,
      }),
    select(data) {
      return data.data;
    },
    enabled: isVisible, // Faqat ko'ringanda ishga tushadi
  });

  // Agar hali ko'rinmagan bo'lsa, bo'sh div qaytarish (scroll uchun joy)
  if (!isVisible) {
    return (
      <section
        ref={sectionRef}
        className="relative custom-container mt-5 min-h-[300px]"
      />
    );
  }

  // Agar loading bo'lmasa va mahsulotlar bo'lmasa, hech narsa ko'rsatmaymiz
  if (!isLoading && (!product || product.results.length === 0)) {
    return null;
  }

  // Agar loading bo'lmasa va faqat "active" mahsulotlar bo'lmasa ham ko'rsatmaymiz
  if (!isLoading && product) {
    const activeProducts = product.results.filter((p) => p.state === 'A');
    if (activeProducts.length === 0) {
      return null;
    }
  }

  if (isLoading) {
    return null;
  }

  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 className="w-full mt-2" setApi={setApi}>
        <CarouselContent className="pr-[12%] sm:pr-0">
          {product &&
            !isLoading &&
            product.results
              .filter((product) => product.state === 'A')
              .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',
        )}
        aria-label="prev images"
        disabled={!canScrollPrev}
        size="icon"
      >
        <ChevronLeft className="size-6" />
      </Button>
    </section>
  );
}
