"use client";
import Image from "next/image";
import { useEffect, useState, useRef } from "react";
import { AWS_CDN_URL } from "@/utils/staticValues";
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import SwiperCore from "swiper";
import { useRouter, useSearchParams } from "next/navigation";

interface VibeProps {
  id: number;
  label: string;
  description: string;
  image: string;
  display_order: number;
}

interface HeroCategoryProps {
  vibeData: VibeProps[];
}

export default function HeroCategory({ vibeData }: HeroCategoryProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const swiperRef = useRef<SwiperCore | null>(null);
  const [isBeginning, setIsBeginning] = useState(true);
  const [isEnd, setIsEnd] = useState(false);
  const [selectedOptions, setSelectedOptions] = useState<string[]>([]);

  const sectionId = "vibe";
  const MAX_VIBE_SELECTIONS = 3;

  // Initialize selectedOptions from URL params
  useEffect(() => {
    const existing = searchParams.get(sectionId)?.split(",").filter(Boolean) || [];
    setSelectedOptions(existing);
  }, [searchParams]);

  function handleCheckboxChange(
    sectionId: string,
    optionValue: string,
    checked: boolean,
  ) {
    // Check if trying to select more than max allowed
    if (checked && selectedOptions.length >= MAX_VIBE_SELECTIONS) {
      return; // Don't allow more than 3 selections
    }

    // Build new params
    const params = new URLSearchParams(searchParams.toString());
    let existing = params.get(sectionId)?.split(",").filter(Boolean) || [];

    if (checked) {
      if (!existing.includes(optionValue)) {
        existing.push(optionValue);
      }
    } else {
      existing = existing.filter((item) => item !== optionValue);
    }

    // Update URL params
    if (existing.length > 0) {
      params.set(sectionId, existing.join(","));
    } else {
      params.delete(sectionId);
    }

    // Use router.push to trigger server re-render
    router.push(`?${params.toString()}`, { scroll: false });

    // Update local state for immediate UI feedback
    setSelectedOptions(existing);
  }

  const onSwiperInit = (swiper: SwiperCore) => {
    swiperRef.current = swiper;
    setIsBeginning(swiper.isBeginning);
    setIsEnd(swiper.isEnd);
  };

  const onSlideChange = () => {
    if (!swiperRef.current) return;
    setIsBeginning(swiperRef.current.isBeginning);
    setIsEnd(swiperRef.current.isEnd);
  };

  const baseButtonStyle =
    "absolute top-1/2 z-10 -translate-y-1/2 bg-gray-100 p-2 text-black transition flex items-center justify-center h-full";

  return (
    <div className="relative z-20 flex flex-col bg-gray-100 mt-12 md:mt-10 py-2">
      <div className="wrapper relative z-20 mx-auto flex w-full flex-col items-center">
        <div className="mx-auto flex w-[92%] flex-col items-center justify-center">
          <Swiper
            slidesPerView={4}
            spaceBetween={3}
            breakpoints={{
              640: { slidesPerView: 5, spaceBetween: 3 },
              768: { slidesPerView: 8, spaceBetween: 3 },
            }}
            navigation={{
              nextEl: ".custom-next",
              prevEl: ".custom-prev",
            }}
            modules={[Navigation]}
            className="fabricCatNavItem"
            onSwiper={onSwiperInit}
            onSlideChange={onSlideChange}
          >
            {vibeData.map((option, optionIdx) => {
              const isSelected = selectedOptions.includes(option.id.toString());
              const isDisabled =
                !isSelected && selectedOptions.length >= MAX_VIBE_SELECTIONS;

              return (
                <SwiperSlide key={option.id}>
                  <label
                    htmlFor={`filter-${optionIdx}`}
                    className={`mx-auto flex my-2 w-full cursor-pointer flex-col items-center gap-1 p-1 md:p-2 transition-all duration-300 md:w-32 ${
                      isSelected
                        ? "ring-2 ring-green-400"
                        : "hover:bg-white/50 hover:shadow-lg"
                    } ${isDisabled ? "cursor-not-allowed opacity-50" : ""}`}
                  >
                    <input
                      value={option.id}
                      checked={isSelected}
                      id={`filter-${optionIdx}`}
                      name="vibes"
                      type="checkbox"
                      className="sr-only"
                      disabled={isDisabled}
                      onChange={(e) =>
                        handleCheckboxChange(
                          sectionId,
                          option.id.toString(),
                          e.target.checked,
                        )
                      }
                    />
                    <Image
                      src={`${AWS_CDN_URL}/${option.image}`}
                      alt={
                        option.description || option.label || "Category image"
                      }
                      width={256}
                      height={256}
                      className="img-responsive"
                      loading="lazy"
                    />
                    <div className="md:text-md/4 text-center text-xs capitalize">
                      {option.label}
                    </div>
                  </label>
                </SwiperSlide>
              );
            })}
          </Swiper>

          {/* Navigation Buttons */}
          <button
            className={`${baseButtonStyle} custom-prev left-0 ${
              isBeginning ? "cursor-not-allowed opacity-25" : "opacity-100"
            }`}
            disabled={isBeginning}
            aria-label="Previous"
          >
            <i
              className="icon-[solar--arrow-left-broken]"
              style={{ width: 24, height: 24 }}
            />
          </button>

          <button
            className={`${baseButtonStyle} custom-next right-0 ${
              isEnd ? "cursor-not-allowed opacity-25" : "opacity-100"
            }`}
            disabled={isEnd}
            aria-label="Next"
          >
            <i
              className="icon-[solar--arrow-right-broken]"
              style={{ width: 24, height: 24 }}
            />
          </button>
        </div>
      </div>
    </div>
  );
}
