'use client';

import Autoplay from 'embla-carousel-autoplay';
import useEmblaCarousel from 'embla-carousel-react';
import { motion } from 'framer-motion';
import { useEffect } from 'react';
import React from 'react';
import { useInView } from 'react-intersection-observer';

import { useBreakpointMd } from '@/hooks/useBreakpoint';

interface CarouselDimensions {
  mobile: number;
  desktop: number;
}

interface InfiniteCarouselProps {
  children?: React.ReactNode;
  itemWidth?: CarouselDimensions;
  itemHeight?: CarouselDimensions;
  containerHeight?: CarouselDimensions;
  autoScroll?: boolean;
  scrollInterval?: number;
  gap?: number;
  align?: 'center' | 'start' | 'end';
  mobileGap?: number;
  stopOnInteraction?: boolean;
  disableAutoplay?: boolean;
}

const InfiniteCarousel = ({
  children,
  itemWidth = { mobile: 334, desktop: 674 },
  itemHeight = { mobile: 451, desktop: 451 },
  containerHeight = { mobile: 450, desktop: 450 },
  autoScroll = false,
  scrollInterval = 3000,
  gap = 11,
  align = 'center',
  mobileGap = 10,
  stopOnInteraction = false,
  disableAutoplay = false,
}: InfiniteCarouselProps) => {
  const isMobile = !useBreakpointMd();
  const { ref, inView } = useInView({ triggerOnce: true, threshold: 0.2 });

  // Create autoplay plugin options
  const autoplayOptions = {
    delay: scrollInterval,
    stopOnInteraction: stopOnInteraction,
    stopOnMouseEnter: true,
    rootNode: (emblaRoot: any) => emblaRoot.parentElement,
  };

  // Update plugins logic to respect disableAutoplay
  const plugins =
    autoScroll && !disableAutoplay ? [Autoplay(autoplayOptions)] : [];

  const [emblaRef, emblaApi] = useEmblaCarousel(
    {
      loop: true,
      align,
      dragFree: isMobile ? false : true,
      containScroll: false,
      skipSnaps: false,
      axis: 'x',
      direction: 'ltr',
      watchDrag: true,
    },
    plugins
  );

  useEffect(() => {
    if (!emblaApi) return;

    let timeoutId: NodeJS.Timeout;
    let isScrolling = false;

    const onWheel = (event: WheelEvent) => {
      // Only prevent default for horizontal scrolling
      if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
        event.preventDefault();
      }

      // Only handle horizontal scrolling
      if (isScrolling || event.deltaX === 0) return;
      isScrolling = true;

      if (event.deltaX > 0) {
        emblaApi.scrollNext();
      } else {
        emblaApi.scrollPrev();
      }

      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        isScrolling = false;
      }, 200);
    };

    const rootNode = emblaApi.rootNode();
    rootNode.addEventListener('wheel', onWheel, { passive: false });

    return () => {
      rootNode.removeEventListener('wheel', onWheel);
      clearTimeout(timeoutId);
    };
  }, [emblaApi]);

  const currentWidth = isMobile ? itemWidth.mobile : itemWidth.desktop;
  const currentHeight = isMobile ? itemHeight.mobile : itemHeight.desktop;
  const currentContainerHeight = isMobile
    ? containerHeight.mobile
    : containerHeight.desktop;

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 40 }}
      animate={inView ? { opacity: 1, y: 0 } : {}}
      transition={{ duration: 0.7, ease: [0.4, 0, 0.2, 1] }}
      className='w-full'
    >
      <div
        className='w-full overflow-hidden'
        style={{ height: `${currentContainerHeight}px` }}
        ref={emblaRef}
      >
        <div
          style={{
            marginLeft: `${isMobile ? mobileGap : gap}px`,
            marginRight: `${isMobile ? mobileGap : gap}px`,
          }}
          className='flex'
        >
          {React.Children.map(children, (child, index) => (
            <div
              key={index}
              style={{
                flex: `0 0 ${currentWidth}px`,
                marginRight: `${isMobile ? mobileGap : gap}px`,
              }}
              className='min-w-0'
            >
              <div
                className='flex items-center justify-center rounded-[20px] text-2xl text-white'
                style={{
                  width: `${currentWidth}px`,
                  height: `${currentHeight}px`,
                }}
              >
                {child}
              </div>
            </div>
          ))}
        </div>
      </div>
    </motion.div>
  );
};

export default InfiniteCarousel;
