"use client";

import * as React from "react";
import useEmblaCarousel from "embla-carousel-react";
import type {
  EmblaCarouselType,
  EmblaOptionsType,
  EmblaPluginType,
} from "embla-carousel";
import { RiArrowLeftLine, RiArrowRightLine } from "@remixicon/react";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

type CarouselProps = React.ComponentProps<"div"> & {
  opts?: EmblaOptionsType;
  plugins?: EmblaPluginType[];
  orientation?: "horizontal" | "vertical";
};

type CarouselContextValue = {
  carouselRef: (node: HTMLDivElement | null) => void;
  api: EmblaCarouselType | undefined;
  scrollPrev: () => void;
  scrollNext: () => void;
  canScrollPrev: boolean;
  canScrollNext: boolean;
};

const CarouselContext = React.createContext<CarouselContextValue | null>(null);

function Carousel({
  className,
  opts,
  plugins,
  orientation = "horizontal",
  children,
  ...props
}: CarouselProps) {
  const [carouselRef, api] = useEmblaCarousel(
    {
      ...opts,
      axis: orientation === "vertical" ? "y" : "x",
    },
    plugins,
  );
  const [canScrollPrev, setCanScrollPrev] = React.useState(false);
  const [canScrollNext, setCanScrollNext] = React.useState(false);

  const scrollPrev = React.useCallback(() => {
    api?.scrollPrev();
  }, [api]);

  const scrollNext = React.useCallback(() => {
    api?.scrollNext();
  }, [api]);

  const onSelect = React.useCallback((apiToUse: EmblaCarouselType) => {
    setCanScrollPrev(apiToUse.canScrollPrev());
    setCanScrollNext(apiToUse.canScrollNext());
  }, []);

  React.useEffect(() => {
    if (!api) {
      return;
    }

    const frame = window.requestAnimationFrame(() => {
      onSelect(api);
    });

    api.on("reInit", onSelect);
    api.on("select", onSelect);

    return () => {
      window.cancelAnimationFrame(frame);
      api.off("reInit", onSelect);
      api.off("select", onSelect);
    };
  }, [api, onSelect]);

  return (
    <CarouselContext.Provider
      value={{
        carouselRef,
        api,
        scrollPrev,
        scrollNext,
        canScrollPrev,
        canScrollNext,
      }}
    >
      <div
        data-slot="carousel"
        className={cn("relative", className)}
        {...props}
      >
        <div className="overflow-hidden" ref={carouselRef}>
          {children}
        </div>
      </div>
    </CarouselContext.Provider>
  );
}

function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="carousel-content"
      className={cn("flex", className)}
      {...props}
    />
  );
}

function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="carousel-item"
      className={cn("min-w-0 shrink-0 grow-0 basis-full", className)}
      {...props}
    />
  );
}

function CarouselPrevious({
  className,
  ...props
}: React.ComponentProps<typeof Button>) {
  const context = React.useContext(CarouselContext);

  if (!context) {
    return null;
  }

  return (
    <Button
      data-slot="carousel-previous"
      size="icon"
      variant="secondary"
      className={cn(
        "absolute left-3 top-1/2 z-10 -translate-y-1/2 rounded-full shadow-lg",
        className,
      )}
      onClick={context.scrollPrev}
      disabled={!context.canScrollPrev}
      {...props}
    >
      <RiArrowLeftLine className="size-4" />
      <span className="sr-only">Previous slide</span>
    </Button>
  );
}

function CarouselNext({
  className,
  ...props
}: React.ComponentProps<typeof Button>) {
  const context = React.useContext(CarouselContext);

  if (!context) {
    return null;
  }

  return (
    <Button
      data-slot="carousel-next"
      size="icon"
      variant="secondary"
      className={cn(
        "absolute right-3 top-1/2 z-10 -translate-y-1/2 rounded-full shadow-lg",
        className,
      )}
      onClick={context.scrollNext}
      disabled={!context.canScrollNext}
      {...props}
    >
      <RiArrowRightLine className="size-4" />
      <span className="sr-only">Next slide</span>
    </Button>
  );
}

export {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselPrevious,
  CarouselNext,
};
