"use client";
import type { VariantProps } from "@karma/cva";
import { cva, cx } from "@karma/cva";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import * as React from "react";

const scrollBarVariants = cva({
  base: "flex touch-none select-none transition-colors",
  variants: {
    orientation: {
      vertical: "h-full w-2.5 border-l border-l-transparent p-[1px]",
      horizontal: "h-2.5 w-full flex-col border-t border-t-transparent p-[1px]",
    },
  },

  defaultVariants: {
    orientation: "vertical",
  },
});

const scrollThumbVariants = cva({
  base: "relative z-10 flex-1 rounded-full",
  variants: {
    variant: {
      primary: "bg-primary",
      accent: "bg-accent",
      muted: "bg-muted",
    },
  },
  defaultVariants: {
    variant: "muted",
  },
});

export type ScrollAreaProps = React.ComponentPropsWithoutRef<
  typeof ScrollAreaPrimitive.Root
>;

export const ScrollArea = React.forwardRef<
  React.ElementRef<typeof ScrollAreaPrimitive.Root>,
  ScrollAreaProps
>(({ className, children, ...props }, ref) => (
  <ScrollAreaPrimitive.Root
    ref={ref}
    className={cx("relative overflow-hidden", className)}
    {...props}
  >
    <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
      {children}
    </ScrollAreaPrimitive.Viewport>
    <ScrollBar />
    <ScrollAreaPrimitive.Corner />
  </ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;

export type ScrollBarProps = React.ComponentPropsWithoutRef<
  typeof ScrollAreaPrimitive.ScrollAreaScrollbar
> &
  VariantProps<typeof scrollBarVariants> &
  VariantProps<typeof scrollThumbVariants>;

export const ScrollBar = React.forwardRef<
  React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
  ScrollBarProps
>(({ className, orientation, variant, ...props }, ref) => (
  <ScrollAreaPrimitive.ScrollAreaScrollbar
    ref={ref}
    orientation={orientation}
    className={cx(
      scrollBarVariants({ orientation }),
      className,
      "rounded-md bg-foreground",
    )}
    {...props}
  >
    <ScrollAreaPrimitive.ScrollAreaThumb
      className={cx(scrollThumbVariants({ variant }))}
    />
  </ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
