'use client';

import { useEffect, useMemo, useState } from 'react';
import Image from 'next/image';

import useEmblaCarousel from 'embla-carousel-react';
import Autoplay from 'embla-carousel-autoplay';

import { cn } from '@/lib/cn';
import { HeroBannerImage } from '@/types/hero-bannerDTO';

interface HeroProps {
  images: HeroBannerImage[];
  title: string;
}

export const Hero = ({ images, title }: HeroProps) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const autoplay = useMemo(
    () =>
      Autoplay({
        delay: 10000,
      }),
    [],
  );

  const [emblaRef, emblaApi] = useEmblaCarousel(
    {
      loop: true,
    },
    [autoplay],
  );

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

    const onSelect = () => {
      setSelectedIndex(emblaApi.selectedScrollSnap());
      autoplay.reset();
    };

    emblaApi.on('select', onSelect);

    onSelect();

    return () => {
      emblaApi.off('select', onSelect);
    };
  }, [autoplay, emblaApi]);

  const handleHeroClick = (event: React.MouseEvent<HTMLElement>) => {
    if (!emblaApi) return;

    const { clientX } = event;
    const { left, width } = event.currentTarget.getBoundingClientRect();

    const clickPosition = clientX - left;
    const middle = width / 2;

    if (clickPosition < middle) {
      emblaApi.scrollPrev();
    } else {
      emblaApi.scrollNext();
    }
    autoplay.stop();
    autoplay.reset();
  };

  return (
    <section className="relative overflow-hidden" onClick={handleHeroClick}>
      {/* Carousel */}
      <div ref={emblaRef}>
        <div className="flex">
          {images.map((slide) => (
            <div key={slide.id} className="relative flex-[0_0_100%]">
              <div className="relative h-screen min-h-full w-full">
                <Image
                  src={slide.image}
                  alt={'Hero banner'}
                  fill
                  priority={slide.order === 1}
                  quality={75}
                  sizes="100vw"
                  className={cn('object-cover object-center')}
                />

                <div className="absolute inset-0 z-10 bg-black/50" />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Fixed content */}
      <div className="absolute inset-0 z-20 flex items-end pb-24 pl-10">
        <div className="flex w-full flex-col gap-6 text-white">
          <h1 className="title-h1 max-w-4/5 font-light uppercase">{title}</h1>

          {/* Dots */}
          <div className="mx-auto mt-6 flex gap-2">
            {images.map((_, index) => (
              <button
                key={index}
                onClick={() => emblaApi?.scrollTo(index)}
                aria-label={`Ir al slide ${index + 1}`}
                className={cn(
                  'h-1 w-12 transition-all duration-300',
                  selectedIndex === index ? 'bg-white' : 'bg-white/50',
                )}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};
