// components/CategoryCarouselInternal.tsx
"use client";

import React, { useEffect } from "react";
import dynamic from "next/dynamic";
import Image from "next/image";
import { useRouter } from "next/navigation";

import categoryImage from "../assets/comming.svg";
import LeftArrow from "../assets/LeftArrow.png";
import RightArrow from "../assets/RightArrow.png";

// Dynamically import Slider
const Slider = dynamic(() => import("react-slick"), {
  ssr: false,
});

interface CategoryData {
  id: number;
  parent_id: number | null;
  name: string;
  icon: string;
  created_at: string;
  listing_images?: string[];
}

interface Props {
  categoryData: CategoryData[];
}

interface ArrowProps {
  className?: string;
  style?: React.CSSProperties;
  onClick?: () => void;
}

const NextArrow: React.FC<ArrowProps> = ({ className, style, onClick }) => (
  <div
    className={`${className} hidden lg:block`}
    style={{
      ...style,
      display: "block",
      position: "absolute",
      right: "-15px",
      top: "50%",
      transform: "translateY(-50%)",
      cursor: "pointer",
      zIndex: 20,
    }}
    onClick={onClick}
  >
    <Image
      unoptimized
      src={RightArrow}
      alt="Next"
      width={40}
      height={40}
      className="h-10 w-28 custom-arrow-left absolute left-0 lg:left-6 top-3 transform -translate-y-1/2 cursor-pointer max-w-10 hidden lg:block"
    />
  </div>
);

const PrevArrow: React.FC<ArrowProps> = ({ className, style, onClick }) => (
  <div
    className={`${className} hidden lg:block`}
    style={{
      ...style,
      display: "block",
      position: "absolute",
      left: "-15px",
      top: "50%",
      transform: "translateY(-50%)",
      cursor: "pointer",
      zIndex: 20,
    }}
    onClick={onClick}
  >
    <Image
      unoptimized
      src={LeftArrow}
      alt="Previous"
      width={40}
      height={40}
      className="h-10 w-28 custom-arrow-left absolute left-0 lg:-left-11 top-3 transform -translate-y-1/2 cursor-pointer max-w-10 hidden lg:block"
    />
  </div>
);

const CategoryCarouselInternal: React.FC<Props> = ({ categoryData }) => {
  const router = useRouter();

  useEffect(() => {
    import("slick-carousel/slick/slick.css");
    import("slick-carousel/slick/slick-theme.css");
  }, []);

  const sliderSettings = {
    dots: false,
    infinite: true,
    speed: 1000,
    autoplay: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    nextArrow: <NextArrow />,
    prevArrow: <PrevArrow />,
    responsive: [
      { breakpoint: 1536, settings: { slidesToShow: 4 } },
      { breakpoint: 1280, settings: { slidesToShow: 3 } },
      { breakpoint: 1024, settings: { slidesToShow: 2 } },
      { breakpoint: 640, settings: { slidesToShow: 1 } },
    ],
  };

  // const imageSliderSettings = {
  //   dots: false,
  //   infinite: true,
  //   speed: 500,
  //   autoplay: true,
  //   slidesToShow: 4,
  //   slidesToScroll: 1,
  //   arrows: false,
  // };

  const getCategoryUrl = (id: number, name: string): string => {
    const categoryName = name
      ?.replace(/[^a-zA-Z0-9\s]/g, "")
      .replace(/\s+/g, "-")
      .toLowerCase();
    return `/${id}/${categoryName}`;
  };

  const handleCategoryClick = (id: number, name: string) => {
    if (id) {
      const url = getCategoryUrl(id, name);
      router.push(url);
    }
  };

  const handleCategoryPrefetch = (id: number, name: string) => {
    const url = getCategoryUrl(id, name);
    router.prefetch(url);
  };

  return (
    <div className="relative category-carousel max-w-7xl mx-auto px-4">
      <Slider {...sliderSettings}>
        {categoryData?.slice(0, 6).map((category) => (
          <div
            key={category?.id}
            onClick={() => handleCategoryClick(category?.id, category?.name)}
            onMouseEnter={() =>
              handleCategoryPrefetch(category?.id, category?.name)
            }
            className="px-2 cursor-pointer relative"
          >
            <div className="relative w-full h-64 rounded-md overflow-hidden">
              <div className="bg-navy absolute z-40 top-0 w-full h-full opacity-70 rounded-md"></div>
              {category?.listing_images?.[0] ? (
                <Image
                  unoptimized
                  src={category?.listing_images[0]}
                  alt="Listing"
                  fill
                  loading="lazy"
                  sizes="400px"
                  className="object-cover rounded-lg"
                />
              ) : (
                <Image
                  unoptimized
                  src={categoryImage}
                  alt="Category"
                  fill
                  loading="lazy"
                  className="w-full h-full object-cover rounded-lg"
                />
              )}

              <h3 className="absolute inset-0 flex items-start text-center justify-center pl-2 pt-5 text-white text-xl font-semibold z-50">
                {category?.name}
              </h3>
            </div>

            {/* Thumbnail preview instead of full slider */}
            {category?.listing_images?.length > 1 && (
              <div className="flex gap-1 mt-2 px-1 overflow-x-auto">
                {category.listing_images.slice(0, 4).map((img, idx) => (
                  <div
                    key={idx}
                    className="relative h-[64px] w-[64px] flex-shrink-0"
                  >
                    <Image
                      unoptimized
                      src={img}
                      alt={`Thumb ${idx}`}
                      fill
                      sizes="64px"
                      loading="lazy"
                      className="object-cover rounded-md"
                    />
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
      </Slider>
    </div>
  );
};

export default CategoryCarouselInternal;
