'use client';

import Lightbox from 'yet-another-react-lightbox';
import Inline from 'yet-another-react-lightbox/plugins/inline';
import 'yet-another-react-lightbox/styles.css';

import YouTubeVideo from '@/components/YoutubeVideo';
import { cn } from '@/lib/utils';

import type { AppLightboxSlide } from './lightboxSlides';

interface YarlInlineCarouselProps {
  slides: AppLightboxSlide[];
  index: number;
  onView?: (index: number) => void;
  onSlideClick?: (index: number) => void;
  className?: string;
}

export default function YarlInlineCarousel({
  slides,
  index,
  onView,
  onSlideClick,
  className,
}: YarlInlineCarouselProps) {
  const hasMultipleSlides = slides.length > 1;

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

  return (
    <Lightbox
      open
      close={() => undefined}
      index={index}
      slides={slides}
      plugins={[Inline]}
      className={cn('h-full w-full', className)}
      carousel={{
        finite: true,
        padding: 0,
        preload: 2,
      }}
      controller={{
        closeOnBackdropClick: false,
      }}
      render={{
        buttonPrev: hasMultipleSlides ? undefined : () => null,
        buttonNext: hasMultipleSlides ? undefined : () => null,
        slide: ({ slide }) => {
          const appSlide = slide as AppLightboxSlide;
          if (!appSlide.videoId) return undefined;

          return (
            <div className="flex h-full w-full items-center justify-center bg-brand-primary">
              <div className="aspect-video w-full max-w-5xl">
                <YouTubeVideo id={appSlide.videoId} title={String(appSlide.title || '')} />
              </div>
            </div>
          );
        },
      }}
      styles={{
        container: {
          backgroundColor: 'transparent',
        },
        slide: {
          padding: 0,
        },
      }}
      on={{
        view: ({ index: nextIndex }) => {
          if (nextIndex !== index) onView?.(nextIndex);
        },
        click: ({ index: clickedIndex }) => onSlideClick?.(clickedIndex),
      }}
    />
  );
}
