"use client";

import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import categoryImage from "../../../../assets/COMMING.svg";
import LeftArrow from "../../../../assets/LeftArrow.png";
import RightArrow from "../../../../assets/RightArrow.png";
import Image from "next/image";
import { useRouter } from "next/navigation";

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

interface CategoryCarouselProps {
  categoryData: CategoryData[];
}

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

// Custom Next Arrow component for react-slick
const NextArrow: React.FC<ArrowProps> = ({ className, style, onClick }) => (
  <div
    className={`${className} hidden lg:block`} // Show only on lg and up
    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>
);

// Custom Prev Arrow component for react-slick
const PrevArrow: React.FC<ArrowProps> = ({ className, style, onClick }) => (
  <div
    className={`${className} hidden lg:block`} // Show only on lg and up
    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 CategoryCarousel: React.FC<CategoryCarouselProps> = ({
  categoryData,
}) => {
  const router = useRouter();

  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);
  };
  // console.log("chehuewhip", categoryData);

  return (
    <div className="relative category-carousel max-w-7xl mx-auto px-4">
      <Slider {...sliderSettings}>
        {categoryData?.map((category) => (
          <div
            key={category?.id}
            onClick={() => handleCategoryClick(category?.id, category?.name)}
            onMouseEnter={() =>
              handleCategoryPrefetch(category?.id, category?.name)
            }
            className="px-2 cursor-pointer relative"
          >
            {/* Main Category Image */}
            <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?.length ? (
                <div className="relative h-full w-full">
                  <Image
                    unoptimized
                    src={category?.listing_images[0]}
                    alt="Listing"
                    fill
                    priority
                    sizes="400px"
                    className="object-cover rounded-lg"
                  />
                </div>
              ) : (
                <Image
                  unoptimized
                  src={categoryImage}
                  alt="Category"
                  fill
                  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>

            {/* Absolute Positioned Slider for Listing Images */}
            {category?.listing_images &&
              category?.listing_images.length > 0 && (
                <div className="absolute bottom-3 left-2 right-2 rounded-md z-50">
                  <Slider {...imageSliderSettings}>
                    {category?.listing_images.map((image, index) =>
                      image ? (
                        <div key={index} className="px-1">
                          <div className="relative h-[70px] w-full">
                            <Image
                              unoptimized
                              src={image}
                              alt={`Listing ${index}`}
                              height={100}
                              width={100}
                              // sizes="64px"
                              // priority
                              className="object-cover h-full w-full rounded-md z-50"
                            />
                          </div>
                        </div>
                      ) : null
                    )}
                  </Slider>
                </div>
              )}
          </div>
        ))}
      </Slider>
    </div>
  );
};

export default CategoryCarousel;
