'use client';

import { getYoutubeThumbnail } from '@/utils/function';
import { VideoItem } from '@/types/section';
import { Play, ChevronLeft, ChevronRight } from 'lucide-react';
import { COMPANY_INFO } from '@/config/contact';
import Image from 'next/image';
import RatingStars from '../RatingStars';
import { useRef, useState, useEffect } from 'react';

export type VideoAspectRatio = 'portrait' | 'landscape';
export type VideoGridCols = 2 | 3 | 4 | 5 | 6;
export type VideoLayout = 'grid' | 'slider';

interface VideoGalleryProps {
  videoList: VideoItem[];
  onSelectVideo: (url: string, aspectRatio: VideoAspectRatio) => void;
  title?: string;
  aspectRatio?: VideoAspectRatio;
  gridCols?: VideoGridCols;
  gradientFrom?: string;
  gradientTo?: string;
  showRating?: boolean;
  layout?: VideoLayout;
}

const gridColsClasses: Record<VideoGridCols, string> = {
  2: 'grid-cols-1 sm:grid-cols-2',
  3: 'grid-cols-1 sm:grid-cols-2 md:grid-cols-3',
  4: 'grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4',
  5: 'grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5',
  6: 'grid-cols-1 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'
};

const sliderWidthClasses: Record<number, string> = {
  2: 'w-1/2',
  3: 'w-[85%] sm:w-1/2 md:w-1/3',
  4: 'w-[85%] sm:w-1/3 md:w-1/4',
  5: 'w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/5',
  6: 'w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/5 xl:w-1/6'
};

const aspectRatioStyles: Record<VideoAspectRatio, { ratio: string; maxHeight: string }> = {
  portrait: { ratio: '9/16', maxHeight: '320px' },
  landscape: { ratio: '16/9', maxHeight: '200px' }
};

export default function VideoGallery({
  videoList,
  onSelectVideo,
  title,
  aspectRatio = 'portrait',
  gridCols = 4,
  gradientFrom = 'from-red-500',
  gradientTo = 'to-red-500',
  showRating = false,
  layout = 'grid'
}: VideoGalleryProps) {
  const aspectStyle = aspectRatioStyles[aspectRatio];
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);

  const checkScroll = () => {
    if (scrollContainerRef.current) {
      const { scrollLeft, scrollWidth, clientWidth } = scrollContainerRef.current;
      setCanScrollLeft(scrollLeft > 0);
      // Use a small tolerance (e.g., 5px) to account for fractional pixel widths
      setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 5);
    }
  };

  useEffect(() => {
    checkScroll();
    window.addEventListener('resize', checkScroll);
    return () => window.removeEventListener('resize', checkScroll);
  }, [videoList]);

  const scroll = (direction: 'left' | 'right') => {
    if (scrollContainerRef.current) {
      const scrollAmount = 300; // Adjust scroll amount as needed
      const newScrollLeft = direction === 'left'
        ? scrollContainerRef.current.scrollLeft - scrollAmount
        : scrollContainerRef.current.scrollLeft + scrollAmount;

      scrollContainerRef.current.scrollTo({
        left: newScrollLeft,
        behavior: 'smooth'
      });
    }
  };

  // Calculate button vertical position to center on video (excluding text/rating)
  const buttonTopClass = aspectRatio === 'portrait' ? 'top-[40%]' : 'top-[30%]';

  return (
    <div className="w-full">
      {title && (
        <div className="mb-6 flex items-center gap-3">
          <div className={`h-8 w-1.5 rounded-full bg-gradient-to-b ${gradientFrom} ${gradientTo}`} />
          <h3 className="text-xl md:text-2xl font-bold text-gray-900 tracking-tight">
            {title}
          </h3>
        </div>
      )}

      {layout === 'grid' ? (
        <div className={`grid ${gridColsClasses[gridCols]} gap-6 md:gap-8`}>
          {videoList.map((video, index) => (
            <VideoCard
              key={index}
              video={video}
              index={index}
              aspectRatio={aspectRatio}
              aspectStyle={aspectStyle}
              onSelectVideo={onSelectVideo}
              showRating={showRating}
            />
          ))}
        </div>
      ) : (
        <div className="relative group/slider">
          {/* Navigation Buttons - Desktop */}
          <button
            onClick={() => scroll('left')}
            className={`hidden md:flex absolute -left-4 ${buttonTopClass} -translate-y-1/2 -translate-x-full z-20 w-12 h-12 bg-white border border-red-100 text-red-600 rounded-full shadow-lg shadow-red-100/50 items-center justify-center hover:bg-red-600 hover:text-white hover:border-red-600 hover:scale-110 transition-all duration-300 ${canScrollLeft ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
            aria-label="Scroll left"
          >
            <ChevronLeft className="w-6 h-6" />
          </button>

          <button
            onClick={() => scroll('right')}
            className={`hidden md:flex absolute -right-4 ${buttonTopClass} -translate-y-1/2 translate-x-full z-20 w-12 h-12 bg-white border border-red-100 text-red-600 rounded-full shadow-lg shadow-red-100/50 items-center justify-center hover:bg-red-600 hover:text-white hover:border-red-600 hover:scale-110 transition-all duration-300 ${canScrollRight ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
            aria-label="Scroll right"
          >
            <ChevronRight className="w-6 h-6" />
          </button>

          {/* Scrollable Container */}
          <div
            ref={scrollContainerRef}
            onScroll={checkScroll}
            className="flex overflow-x-auto pb-8 gap-2 snap-x snap-mandatory scrollbar-hide -mx-4 px-4 md:mx-0 md:px-0 ml-0"
          >
            {videoList.map((video, index) => (
              <div key={index} className={`flex-none ${sliderWidthClasses[gridCols] || sliderWidthClasses[4]} snap-start pl-1`}>
                <VideoCard
                  video={video}
                  index={index}
                  aspectRatio={aspectRatio}
                  aspectStyle={aspectStyle}
                  onSelectVideo={onSelectVideo}
                  showRating={showRating}
                />
              </div>
            ))}
          </div>

          {/* Gradient Fade for scroll indication (optional) */}

        </div>
      )}
    </div>
  );
}

function VideoCard({ video, index, aspectRatio, aspectStyle, onSelectVideo, showRating }: any) {
  return (
    <div
      onClick={() => onSelectVideo(video.url, aspectRatio)}
      className="group cursor-pointer rounded-2xl overflow-hidden bg-white relative h-full flex flex-col transition-all duration-500 hover:-translate-y-1 hover:shadow-[0_20px_40px_-15px_rgba(0,0,0,0.1)] ring-1 ring-gray-900/5"
    >
      {/* Video Thumbnail */}
      <div
        className="relative w-full overflow-hidden bg-gray-100"
        style={{ aspectRatio: aspectStyle.ratio }}
      >
        <Image
          src={getYoutubeThumbnail(video.url)}
          alt={video.title}
          fill
          className="object-cover object-center transform group-hover:scale-105 transition-transform duration-700 ease-out"
          loading="lazy"
          unoptimized
          sizes="100vw"
        />

        {/* Play Button Overlay */}
        <div className="absolute inset-0 bg-black/20 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center">
          <div className="w-12 h-12 md:w-14 md:h-14 rounded-full bg-white/20 backdrop-blur-md border border-white/30 flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform duration-300 group-hover:bg-red-600 group-hover:border-red-500">
            <Play className="w-5 h-5 md:w-6 md:h-6 text-white ml-1" fill="currentColor" />
          </div>
        </div>

        {/* New Badge - More subtle */}
        <div className="absolute top-3 left-3">
          <span className="bg-white/90 backdrop-blur-sm text-slate-900 text-[10px] font-bold px-2.5 py-1 rounded-full shadow-sm border border-white/50">
            NEW
          </span>
        </div>
        {/* Overlay Gradient for Text */}
        <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/20 to-transparent opacity-60 group-hover:opacity-80 transition-opacity duration-300" />

        {/* Video Info Overlay */}
        <div className="absolute bottom-0 left-0 w-full p-4 flex flex-col justify-end z-10">
          <h3
            className="text-sm md:text-base font-bold text-white mb-2 truncate leading-snug drop-shadow-md"
            title={video.title}
          >
            {video.title}
          </h3>

          {showRating && video.rating !== undefined && (
            <div className="flex items-center">
              <RatingStars rating={video.rating} textColor="text-white/80" />
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
