import { cn } from '@/lib/utils/tw-merge'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import React, {
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react'

const MIN_CAROUSEL_ITEMS = 4

interface CarouselProps {
  items: any[]
  itemWidth?: number
  gap?: number
  autoPlayInterval?: number
  className?: string
  showControls?: boolean
  showIndicators?: boolean
  loading?: boolean
  skeletonCount?: number
  containerClassName?: string
  indicatorSize?: number
  renderItem: (item: any, index: number) => ReactNode
  renderSkeleton?: () => ReactNode
}

const Carousel: React.FC<CarouselProps> = ({
  items,
  renderItem,
  itemWidth = 280,
  gap = 24,
  autoPlayInterval = 3000,
  className = '',
  showControls = true,
  showIndicators = true,
  loading = false,
  renderSkeleton,
  skeletonCount = 8,
  containerClassName = 'gap-6',
  indicatorSize = 6,
}) => {
  const scrollContainer = useRef<HTMLDivElement>(null)
  const [isDragging, setIsDragging] = useState(false)
  const [startX, setStartX] = useState(0)
  const [scrollLeft, setScrollLeft] = useState(0)
  const [isPaused, setIsPaused] = useState(false)
  const [currentIndex, setCurrentIndex] = useState(0)

  // For items less than 4, duplicate them to fill the carousel
  let repeatCount: number = 0

  if (items?.length) {
    if (items.length < MIN_CAROUSEL_ITEMS) {
      repeatCount = Math.ceil(MIN_CAROUSEL_ITEMS / items.length)
    } else {
      repeatCount = 1
    }
  }

  const extendedItems = Array(repeatCount)
    .fill(items)
    .flat()
    .concat(items.slice(0, 3))

  const scrollToIndex = useCallback(
    (index: number, behavior: ScrollBehavior = 'smooth') => {
      if (scrollContainer.current) {
        const scrollPosition = index * (itemWidth + gap)
        scrollContainer.current.scrollTo({
          left: scrollPosition,
          behavior,
        })
      }
    },
    [itemWidth, gap],
  )

  // Handle infinite scroll transition
  const handleInfiniteScroll = useCallback(() => {
    if (scrollContainer.current) {
      const totalWidth = (itemWidth + gap) * items.length
      const currentScroll = scrollContainer.current.scrollLeft

      // If we're near the end (showing cloned items)
      if (currentScroll >= totalWidth - (itemWidth + gap)) {
        // Reset to the real first item (without animation)
        requestAnimationFrame(() => {
          if (scrollContainer.current) {
            scrollContainer.current.style.scrollBehavior = 'auto'
            scrollContainer.current.scrollLeft = 0
            requestAnimationFrame(() => {
              if (scrollContainer.current) {
                scrollContainer.current.style.scrollBehavior = 'smooth'
              }
            })
          }
        })
        setCurrentIndex(0)
      }
    }
  }, [items.length, itemWidth, gap])

  // Auto-scroll functionality
  useEffect(() => {
    if (loading || isPaused || items.length <= 1) return

    const interval = setInterval(() => {
      if (scrollContainer.current) {
        const nextIndex = (currentIndex + 1) % items.length
        setCurrentIndex(nextIndex)
        scrollToIndex(nextIndex)
      }
    }, autoPlayInterval)

    return () => clearInterval(interval)
  }, [
    currentIndex,
    isPaused,
    loading,
    items.length,
    autoPlayInterval,
    scrollToIndex,
  ])

  const scroll = (direction: 'left' | 'right') => {
    const nextIndex =
      direction === 'left'
        ? (currentIndex - 1 + items.length) % items.length
        : (currentIndex + 1) % items.length
    setCurrentIndex(nextIndex)
    scrollToIndex(nextIndex)
  }

  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (!scrollContainer.current) return

    setIsDragging(true)
    setStartX(e.pageX - scrollContainer.current.offsetLeft)
    setScrollLeft(scrollContainer.current.scrollLeft)

    // Change cursor style
    if (scrollContainer.current) {
      scrollContainer.current.style.cursor = 'grabbing'
      scrollContainer.current.style.userSelect = 'none'
    }
  }, [])

  const handleMouseUp = useCallback(() => {
    setIsDragging(false)

    // Reset cursor style
    if (scrollContainer.current) {
      scrollContainer.current.style.cursor = 'grab'
      scrollContainer.current.style.userSelect = ''
    }
  }, [])

  const handleMouseMove = useCallback(
    (e: React.MouseEvent) => {
      if (!isDragging || !scrollContainer.current) return

      e.preventDefault()
      const x = e.pageX - scrollContainer.current.offsetLeft
      const walk = (x - startX) * 2 // Multiply by 2 for faster scrolling
      scrollContainer.current.scrollLeft = scrollLeft - walk
    },
    [isDragging, startX, scrollLeft],
  )

  const handleMouseLeave = useCallback(() => {
    setIsDragging(false)

    // Reset cursor style
    if (scrollContainer.current) {
      scrollContainer.current.style.cursor = 'grab'
      scrollContainer.current.style.userSelect = ''
    }
  }, [])

  const handleScroll = useCallback(() => {
    if (scrollContainer.current) {
      const index =
        Math.round(scrollContainer.current.scrollLeft / (itemWidth + gap)) %
        items.length
      setCurrentIndex(index)
      handleInfiniteScroll()
    }
  }, [items.length, itemWidth, gap, handleInfiniteScroll])

  return (
    <div className={`relative ${className}`}>
      {showControls && (
        <>
          <button
            onClick={() => scroll('left')}
            className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-4 z-10 bg-white rounded-full p-2 shadow-lg hover:bg-gray-50 transition-colors cursor-pointer"
          >
            <ChevronLeft
              className={cn(
                'text-blue-800',
                `w-${indicatorSize} h-${indicatorSize}`,
              )}
            />
          </button>

          <button
            onClick={() => scroll('right')}
            className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-4 z-10 bg-white rounded-full p-2 shadow-lg hover:bg-gray-50 transition-colors cursor-pointer"
          >
            <ChevronRight
              className={cn(
                'text-blue-800',
                `w-${indicatorSize} h-${indicatorSize}`,
              )}
            />
          </button>
        </>
      )}

      <div
        ref={scrollContainer}
        className={cn(
          `flex overflow-x-auto pb-4 snap-x snap-mandatory scrollbar-hide cursor-grab`,
          containerClassName,
        )}
        style={{
          scrollbarWidth: 'none',
          msOverflowStyle: 'none',
          WebkitOverflowScrolling: 'touch',
          scrollBehavior: 'smooth',
        }}
        onMouseDown={handleMouseDown}
        onMouseUp={handleMouseUp}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}
        onMouseEnter={() => setIsPaused(true)}
        onScroll={handleScroll}
      >
        {loading
          ? Array(skeletonCount)
              .fill(null)
              .map((_, index) => (
                <div
                  key={index}
                  className="flex-none select-none"
                  style={{ width: `${itemWidth}px` }}
                >
                  {renderSkeleton?.()}
                </div>
              ))
          : extendedItems.map((item, index) => (
              <div
                key={`${index}`}
                className="flex-none snap-start select-none"
                style={{ width: `${itemWidth}px` }}
              >
                {renderItem(item, index)}
              </div>
            ))}
      </div>

      {showIndicators && items.length > 1 && (
        <div className="flex justify-center gap-2 mt-4">
          {items.map((_, index) => (
            <button
              key={index}
              className={`w-2 h-2 rounded-full transition-all ${
                currentIndex === index ? 'bg-blue-800 w-4' : 'bg-gray-300'
              }`}
              onClick={() => {
                setCurrentIndex(index)
                scrollToIndex(index)
              }}
            />
          ))}
        </div>
      )}
    </div>
  )
}

export default Carousel
