'use client';

import { useEffect, useState } from 'react';
import { twMerge } from 'tailwind-merge';

interface SimpleBannerCarouselProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  className?: string;
  autoPlay?: boolean;
  autoPlayDelay?: number;
}

export const SimpleBannerCarousel = <T,>({
  items,
  renderItem,
  className,
  autoPlay = false,
  autoPlayDelay = 5000,
}: SimpleBannerCarouselProps<T>) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [touchStart, setTouchStart] = useState<number | null>(null);
  const [touchEnd, setTouchEnd] = useState<number | null>(null);

  // Auto-advance functionality
  useEffect(() => {
    if (!autoPlay || items.length <= 1) return;

    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % items.length);
    }, autoPlayDelay);

    return () => clearInterval(interval);
  }, [autoPlay, autoPlayDelay, items.length]);

  // Touch swipe handlers
  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchEnd(null);
    setTouchStart(e.targetTouches[0].clientX);
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    setTouchEnd(e.targetTouches[0].clientX);
  };

  const handleTouchEnd = () => {
    if (!touchStart || !touchEnd) return;

    const distance = touchStart - touchEnd;
    const isLeftSwipe = distance > 50;
    const isRightSwipe = distance < -50;

    if (isLeftSwipe && currentIndex < items.length - 1) {
      setCurrentIndex(currentIndex + 1);
    }
    if (isRightSwipe && currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft' && currentIndex > 0) {
        setCurrentIndex(currentIndex - 1);
      }
      if (e.key === 'ArrowRight' && currentIndex < items.length - 1) {
        setCurrentIndex(currentIndex + 1);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [currentIndex, items.length]);

  if (items.length === 0) return null;

  return (
    <div
      className={twMerge('relative overflow-hidden rounded-2xl', className)}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
      tabIndex={0} // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
      role='region'
      aria-label='Carousel'
    >
      {/* Items container */}
      <div
        className='flex transition-transform duration-300 ease-in-out'
        style={{ transform: `translateX(-${currentIndex * 100}%)` }}
      >
        {items.map((item, index) => (
          <div key={index} className='w-full flex-shrink-0'>
            {renderItem(item, index)}
          </div>
        ))}
      </div>

      {/* Navigation bars */}
      {items.length > 1 && (
        <div className='absolute right-0 bottom-0 left-0 flex gap-1 px-4 pt-8 pb-2'>
          {items.map((_, index) => (
            <button
              key={index}
              onClick={() => setCurrentIndex(index)}
              className={twMerge(
                'h-1 flex-1 rounded-full transition-colors duration-200 focus:ring-2 focus:ring-white/50 focus:outline-none',
                currentIndex === index
                  ? 'bg-white'
                  : 'bg-white/30 hover:bg-white/50'
              )}
              aria-label={`Go to slide ${index + 1}`}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default SimpleBannerCarousel;
