"use client";
import { FC, ReactNode, useRef, useState, useCallback, useEffect } from "react";
import { FaChevronLeft, FaChevronRight } from "react-icons/fa";

type CarouselOptions = {
  itemsPerView?: number;
  itemsPerViewMobile?: number;
  itemsPerViewTablet?: number;
};

type Props = {
  children: ReactNode[];
  options?: CarouselOptions;
  className?: string;
  heading?: string;
  icon?: ReactNode;
  colors?: keyof typeof colorsMap;
  fluid?: boolean;
};

export const Carousel: FC<Props> = ({
  children,
  options = {},
  className = "",
  heading,
  icon,
  colors = "yellow",
  fluid = false,
}) => {
  const {
    itemsPerView = 4,
    itemsPerViewMobile = 1,
    itemsPerViewTablet = 2,
  } = options;

  const [perView, setPerView] = useState(itemsPerView);
  const [currentPage, setCurrentPage] = useState(0);
  const totalPages = Math.ceil(children.length / perView);

  useEffect(() => {
    const handleResize = () => {
      if (window.matchMedia("(min-width: 1024px)").matches) {
        setPerView(itemsPerView);
      } else if (window.matchMedia("(min-width: 768px)").matches) {
        setPerView(itemsPerViewTablet);
      } else {
        setPerView(itemsPerViewMobile);
      }
    };

    handleResize();
    window.addEventListener("resize", handleResize);

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const nextPage = () => {
    setCurrentPage((prev) => (prev + 1) % totalPages);
  };

  const prevPage = () => {
    setCurrentPage((prev) => (prev - 1 + totalPages) % totalPages);
  };

  const currentMovies = children.slice(
    currentPage * perView,
    (currentPage + 1) * perView
  );

  return (
    <div className={`${fluid ? "max-w-full px-4" : "container"}`}>
      <div className="flex items-center justify-between mb-8 flex-wrap">
        {heading && (
          <div className="flex items-center gap-3">
            {icon && (
              <div
                className={`hidden sm:block p-2 rounded-lg ${colorsMap[colors]}`}
              >
                {icon}
              </div>
            )}
            <h2
              className={`text-3xl font-bold ${colorsMap[colors]} bg-clip-text text-transparent text-center sm:text-left`}
            >
              {heading}
            </h2>
          </div>
        )}

        {totalPages > 1 && (
          <div className="flex gap-2 mx-auto mt-4 sm:mt-0 sm:mr-0 sm:ml-auto">
            <button
              onClick={prevPage}
              className={`cursor-pointer p-3 rounded-full ${colorsMap[colors]} text-white transition-all duration-300`}
            >
              <FaChevronLeft size={16} />
            </button>
            <button
              onClick={nextPage}
              className={`cursor-pointer p-3 rounded-full ${colorsMap[colors]} text-white transition-all duration-300 `}
            >
              <FaChevronRight size={16} />
            </button>
          </div>
        )}
      </div>

      <div
        className="grid gap-6 grid-cols-[repeat(var(--i-sm),1fr)] md:grid-cols-[repeat(var(--i-md),1fr)] lg:grid-cols-[repeat(var(--i-lg),1fr)]"
        style={
          {
            "--i-sm": itemsPerViewMobile,
            "--i-md": itemsPerViewTablet,
            "--i-lg": itemsPerView,
          } as React.CSSProperties
        }
      >
        {currentMovies}
      </div>

      {totalPages > 1 && (
        <div className="flex justify-center mt-8">
          <div className="flex gap-2 flex-wrap justify-center">
            {Array.from({ length: totalPages }, (_, i) => (
              <button
                key={i}
                onClick={() => setCurrentPage(i)}
                className={`cursor-pointer w-3 h-3 rounded-full transition-all duration-300 ${
                  currentPage === i
                    ? `${colorsMap[colors]} scale-110`
                    : "bg-white/30 hover:bg-white/50"
                }`}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

const colorsMap = {
  yellow: "bg-gradient-to-r from-yellow-400 to-orange-400",
  blue: "bg-gradient-to-r from-blue-400 to-purple-400",
  green: "bg-gradient-to-r from-green-400 to-teal-400",
  red: "bg-gradient-to-r from-red-400 to-pink-400",
  purple: "bg-gradient-to-r from-purple-400 to-pink-400",
  orange: "bg-gradient-to-r from-orange-400 to-yellow-400",
  pink: "bg-gradient-to-r from-pink-400 to-purple-400",
  teal: "bg-gradient-to-r from-teal-400 to-green-400",
  gray: "bg-gradient-to-r from-gray-400 to-gray-400",
};
