"use client";

import React, { useCallback, useState, useEffect, useRef } from "react";
import useEmblaCarousel from "embla-carousel-react";
import { cn } from "@/lib/utils";
import Image from "next/image";
import { debounce } from "lodash";
import { Heart, HeartPulse, Mail, Megaphone, User } from "lucide-react";

const InfographicsSection: React.FC = () => {
  const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false });
  const [selectedIndex, setSelectedIndex] = useState(0);
  const autoplayRef = useRef<NodeJS.Timeout | null>(null);

  const scrollToSlide = useCallback(
    (index: number) => {
      if (emblaApi) {
        emblaApi.scrollTo(index);
      }
    },
    [emblaApi]
  );

  const handleSelect = useCallback(
    debounce(() => {
      if (!emblaApi) return;
      setSelectedIndex(emblaApi.selectedScrollSnap());
    }, 100),
    [emblaApi]
  );

  const autoplay = useCallback(() => {
    if (autoplayRef.current) return;
    autoplayRef.current = setInterval(() => {
      if (!emblaApi) return;
      const nextIndex = (selectedIndex + 1) % emblaApi.scrollSnapList().length;
      emblaApi.scrollTo(nextIndex);
    }, 3000);
  }, [emblaApi, selectedIndex]);

  useEffect(() => {
    if (emblaApi) {
      emblaApi.on("select", handleSelect);
      emblaApi.on("reInit", handleSelect);
      autoplay();
    }

    return () => {
      if (autoplayRef.current) clearInterval(autoplayRef.current);
    };
  }, [emblaApi, handleSelect, autoplay]);

  const icons = [
    { label: "Speaker", color: "bg-green-500", icon: <Megaphone /> },
    { label: "Heart", color: "bg-red-500", icon: <Heart /> },
    { label: "User", color: "bg-black", icon: <User /> },
    { label: "Email", color: "bg-blue-400", icon: <Mail /> },
    { label: "Health", color: "bg-primary", icon: <HeartPulse /> },
  ];

  const slides = [
    {
      description:
        "Lorem ipsum dolor sit amet consectetur. Etiam massa bibendum lorem pellentesque a. Condimentum enim purus aliquet velit in allentesque fermentum venenatis luctus nulla. Lorem ipsum dolor sit amet consectetur. Etiam massa bibendum lorem pellentesque a. Condimentum enim purus aliquet velit in allentesque fermentum venenatis luctus nulla.",
      imgSrc: "/assets/images/iphone-1.svg",
    },
    {
      description:
        "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.",
      imgSrc: "/assets/images/iphone-1.svg",
    },
    {
      description:
        "Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      imgSrc: "/assets/images/iphone-1.svg",
    },
    {
      description:
        "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
      imgSrc: "/assets/images/iphone-1.svg",
    },
    {
      description:
        "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
      imgSrc: "/assets/images/iphone-1.svg",
    },
  ];

  return (
    <section className="relative container bg-primary-50 md:rounded-xl mx-auto py-6 md:py-12">
      <div className="flex flex-col md:flex-row h-full">
        <div className="hidden md:flex flex-col w-1/2">
          <div className="flex flex-col justify-between h-full">
            <h2 className="mb-4">Condimentum enim purus aliquet.</h2>

            <div className="flex h-full gap-y-1 gap-x-4">
              {icons.map((icon, index) => (
                <div
                  key={index}
                  className="relative text-white flex h-full flex-col items-center"
                >
                  <button
                    onClick={() => scrollToSlide(index)}
                    className={cn(
                      "cursor-pointer rounded-full h-12 w-12 flex items-center justify-center transition-transform transform hover:scale-110",
                      icon.color,
                      selectedIndex === index && "border-2 border-white"
                    )}
                    aria-label={icon.label}
                  >
                    {icon.icon}
                  </button>
                  <div
                    className={cn(
                      "absolute left-1/2 transform -translate-x-1/2 transition-all",
                      "bg-primary",
                      selectedIndex === index
                        ? "w-[1px] bottom-0 top-14"
                        : "w-[1px] bottom-0 h-0"
                    )}
                  />
                  <div
                    className={cn(
                      "absolute rounded-full left-1/2 transform -translate-x-1/2",
                      "bg-primary",
                      selectedIndex === index
                        ? "w-1.5 h-1.5 top-14"
                        : "w-0.5 bottom-0 h-0"
                    )}
                  />
                </div>
              ))}
            </div>
            <div className="mt-auto">
              <p className="text-lg">{slides[selectedIndex].description}</p>
            </div>
          </div>
        </div>

        <div className="w-full md:w-1/2">
          <h2 className="mb-4 block md:hidden">
            Condimentum enim purus aliquet.
          </h2>
          <div className="overflow-hidden" ref={emblaRef}>
            <div className="flex">
              {slides.map((slide, index) => (
                <div
                  key={index}
                  className="min-w-0 flex-[0_0_100%] flex flex-col h-fit md:flex-row items-center p-4"
                >
                  <div className="block md:hidden mb-4">
                    <div className="flex h-full gap-y-1 mb-4">
                      <div className="relative text-white flex h-full flex-col items-center">
                        <button
                          className={cn(
                            "cursor-pointer rounded-full h-12 w-12 flex items-center justify-center transition-transform transform hover:scale-110",
                            icons[selectedIndex].color
                          )}
                          aria-label={icons[selectedIndex].label}
                        >
                          {icons[selectedIndex].icon}
                        </button>
                      </div>
                    </div>
                    <p className="text-base">{slide.description}</p>
                  </div>
                  <div className="w-full flex justify-center">
                    <Image
                      height={500}
                      width={500}
                      src={slide.imgSrc}
                      alt={`Slide ${index + 1}`}
                      className="rounded-lg w-[300px]"
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="flex justify-center space-x-2 mt-4 md:hidden">
            {slides.map((_, index) => (
              <button
                key={index}
                onClick={() => scrollToSlide(index)}
                className={cn(
                  "h-3 w-3 rounded-full transition-colors",
                  selectedIndex === index ? "bg-primary" : "bg-neutral-300"
                )}
                aria-label={`Go to slide ${index + 1}`}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

export default InfographicsSection;
