"use client";

import useEmblaCarousel from "embla-carousel-react";

import { useCallback, useEffect, useRef } from "react";
import TestimonialCard from "./Testimonial";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { debounce } from "lodash";

const TestimonialsCarousel = ({ testimonials }: { testimonials: any[] }) => {
  const [emblaRef, emblaApi] = useEmblaCarousel();
  const prevBtnRef = useRef<HTMLButtonElement>(null);
  const nextBtnRef = useRef<HTMLButtonElement>(null);

  const scrollPrev = useCallback(() => {
    if (emblaApi) emblaApi.scrollPrev();
  }, [emblaApi]);

  const scrollNext = useCallback(() => {
    if (emblaApi) emblaApi.scrollNext();
  }, [emblaApi]);

  useEffect(() => {
    if (!emblaApi) return;
    emblaApi.on(
      "scroll",
      debounce(() => {
        emblaApi.canScrollPrev()
          ? prevBtnRef.current?.classList.add("enabled")
          : prevBtnRef.current?.classList.remove("enabled");
        emblaApi.canScrollNext()
          ? nextBtnRef.current?.classList.add("enabled")
          : nextBtnRef.current?.classList.remove("enabled");
      }, 10)
    );
  }, [emblaApi]);
  return (
    <div className="testimonials embla">
      <div ref={emblaRef} className="embla__viewport">
        <ul className="testimonials__list embla__container">
          {testimonials.map((testimonial, i) => (
            <li key={testimonial.name} className="embla__slide">
              <TestimonialCard testimonial={testimonial} />
            </li>
          ))}
        </ul>
      </div>
      <div className="testimonials__controls">
        <button
          ref={prevBtnRef}
          className="btn testimonials__control-btn embla__prev"
          onClick={scrollPrev}
        >
          <ChevronLeftIcon className="icon" />
        </button>
        <button
          ref={nextBtnRef}
          className="btn testimonials__control-btn embla__next enabled"
          onClick={scrollNext}
        >
          <ChevronRightIcon className="icon" />
        </button>
      </div>
    </div>
  );
};
export default TestimonialsCarousel;
