"use client";

import { useCallback, useEffect, useRef, useState, useMemo, memo } from "react";
import { motion, useInView } from "framer-motion";
import useEmblaCarousel from "embla-carousel-react";
import Autoplay from "embla-carousel-autoplay";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { Divider } from "@heroui/react";
import data from "@/data/home.json";
import { useLocale } from "next-intl";
import { ServiceCard } from "../services";

// Animation variants - moved outside component to prevent recreation
const EASE_OUT_EXPO = [0.22, 1, 0.36, 1] as const;

const headerVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.6, ease: EASE_OUT_EXPO },
  },
};

const carouselVariants = {
  hidden: { opacity: 0, y: 30 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.7, delay: 0.2, ease: EASE_OUT_EXPO },
  },
};

// Memoized button component to prevent unnecessary re-renders
const NavButton = memo(
  ({
    onClick,
    disabled,
    direction,
    ariaLabel,
  }: {
    onClick: () => void;
    disabled: boolean;
    direction: "prev" | "next";
    ariaLabel: string;
  }) => {
    const Icon = direction === "prev" ? ChevronLeft : ChevronRight;

    return (
      <button
        onClick={onClick}
        disabled={disabled}
        className="flex items-center justify-center size-8 md:size-12 rounded-full border-2 border-white/50 text-white transition-all hover:border-white hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
        aria-label={ariaLabel}
      >
        <Icon className="size-4 md:size-6" />
      </button>
    );
  }
);

NavButton.displayName = "NavButton";

export const HomeServicesSection = () => {
  const locale = useLocale();
  const sectionRef = useRef(null);
  const isInView = useInView(sectionRef, { once: true, margin: "-100px" });

  // Memoize autoplay plugin to prevent recreation
  const autoplayPlugin = useMemo(
    () =>
      Autoplay({
        delay: 3000,
        stopOnInteraction: false,
        stopOnMouseEnter: true,
      }),
    []
  );

  const [emblaRef, emblaApi] = useEmblaCarousel(
    {
      align: "start",
      loop: true,
      skipSnaps: false,
      dragFree: false,
    },
    [autoplayPlugin]
  );

  const [canScrollPrev, setCanScrollPrev] = useState(false);
  const [canScrollNext, setCanScrollNext] = useState(false);

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

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

  const onSelect = useCallback(() => {
    if (!emblaApi) return;
    setCanScrollPrev(emblaApi.canScrollPrev());
    setCanScrollNext(emblaApi.canScrollNext());
  }, [emblaApi]);

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

    onSelect();
    emblaApi.on("select", onSelect).on("reInit", onSelect);

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

  // Memoize locale-dependent data
  const { title, subtitle, services } = useMemo(() => {
    const servicesData = data?.services;
    const isArabic = locale === "ar";

    return {
      title: isArabic ? servicesData?.title_ar : servicesData?.title_en,
      subtitle: isArabic
        ? servicesData?.subtitle_ar
        : servicesData?.subtitle_en,
      services:
        servicesData?.items?.map((item) => ({
          title: isArabic ? item.title_ar : item.title_en,
          description: isArabic ? item.description_ar : item.description_en,
          image: item.image,
          slug: item?.key,
        })) || [],
    };
  }, [locale]);

  return (
    <motion.section
      ref={sectionRef}
      initial="hidden"
      animate={isInView ? "visible" : "hidden"}
      className="bg-primary m-4 md:m-6 py-9 rounded-4xl"
    >
      <div className="custom-container space-y-6">
        {/* Header */}
        <motion.div variants={headerVariants} className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="h3Text text-secondary">{title}</h2>

            {/* Navigation Buttons */}
            <div className="flex items-center gap-3">
              <NavButton
                onClick={scrollPrev}
                disabled={!canScrollPrev}
                direction="prev"
                ariaLabel="Previous slide"
              />
              <NavButton
                onClick={scrollNext}
                disabled={!canScrollNext}
                direction="next"
                ariaLabel="Next slide"
              />
            </div>
          </div>

          <p className="h6Text text-white max-w-2xl">{subtitle}</p>

          <Divider className="bg-white/50 w-1/2" />
        </motion.div>

        {/* Carousel */}
        <motion.div
          variants={carouselVariants}
          className="overflow-hidden mt-6"
          ref={emblaRef}
        >
          <div className="flex gap-4 md:gap-6 px-4 md:px-6">
            {services?.map((service, index) => (
              <div
                key={`service-${index}`}
                className="min-w-0 basis-full min-[500px]:basis-1/2 lg:basis-1/3 xl:basis-1/4 shrink-0"
              >
                <ServiceCard service={service} />
              </div>
            ))}
          </div>
        </motion.div>
      </div>
    </motion.section>
  );
};
