"use client";

import cx from "classnames";
import React, { HTMLAttributes, ReactNode } from "react";
import { useStatic } from "@/utils/hooks";
import { Icon } from "../Icon";
import CarouselStatic from "./Carousel.static";
import { CarouselItem } from "./CarouselItem";
import {
  CLASS_DOTS,
  CLASS_NEXT,
  CLASS_PREV,
  CLASS_ROOT,
  CLASS_SCROLLBAR,
  CLASS_SCROLLBAR_DRAG,
  CLASS_TRACK,
  CLASS_VIEWPORT,
  CLASS_VIEWPORT_WRAPPER,
} from "./constants";

interface CarouselProps extends HTMLAttributes<HTMLDivElement> {
  /** Swiper.js (https://swiperjs.com/) options object */
  swiperOptions?: Record<string, any>;
  /** Carousel items */
  items: ReactNode[];
  /** Always show scrollbar and hide dots */
  showScrollbar?: boolean;
  /** Make carousel bleed to the right edge of screen while keeping left aligned with container */
  bleedRight?: boolean;
  className?: string;
}

const Carousel: React.FC<CarouselProps> = ({
  className,
  swiperOptions,
  items,
  showScrollbar = false,
  bleedRight = false,
  ...other
}) => {
  const [carouselRef] = useStatic(CarouselStatic);

  const carouselItems = items.map((item, i) => (
    <CarouselItem key={i.toString()}>{item}</CarouselItem>
  ));

  const classes = cx(CLASS_ROOT, className, {
    [`${CLASS_ROOT}--scrollbar`]: showScrollbar,
    [`${CLASS_ROOT}--bleed-right`]: bleedRight,
  });

  const elementClasses = {
    prev: cx(CLASS_PREV),
    next: cx(CLASS_NEXT),
    dots: cx(CLASS_DOTS, showScrollbar ? "hide" : "show-md"),
  };

  // Only override pagination when showScrollbar is true
  const customSwiperOptions = showScrollbar
    ? {
        pagination: {
          enabled: false,
        },
        ...swiperOptions,
      }
    : swiperOptions;

  return (
    <div
      className={classes}
      ref={carouselRef}
      data-carousel
      {...(showScrollbar || swiperOptions
        ? { "data-swiper-options": JSON.stringify(customSwiperOptions) }
        : {})}
      {...other}
    >
      <div className={CLASS_VIEWPORT_WRAPPER}>
        <div className={CLASS_VIEWPORT}>
          <div className={CLASS_TRACK}>{carouselItems}</div>
        </div>
        {showScrollbar ? null : (
          <>
            <button
              type="button"
              aria-label="Naspäť"
              className={elementClasses.prev}
            >
              <Icon size="medium" name="chevron-left" />
            </button>
            <button
              type="button"
              aria-label="Ďalej"
              className={elementClasses.next}
            >
              <Icon size="medium" name="chevron-right" />
            </button>
          </>
        )}
      </div>

      {!showScrollbar && <div role="tablist" className={elementClasses.dots} />}

      <div className={cx(CLASS_SCROLLBAR, !showScrollbar && "hide-md")}>
        <div className={CLASS_SCROLLBAR_DRAG} />
      </div>
    </div>
  );
};

Carousel.displayName = "Carousel";

export { Carousel };
