import * as React from 'react'
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'
import tw, { TwStyle } from 'twin.macro'

type OrientationType = 'vertical' | 'horizontal'
const ORIENTATION_MAP = {
  vertical: tw`h-full w-2.5 border-l border-l-transparent p-[1px]`,
  horizontal: tw`h-2.5 border-t border-t-transparent p-[1px]`,
} satisfies Record<OrientationType, TwStyle>

const ScrollBar = React.forwardRef<
  React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
  React.ComponentPropsWithoutRef<
    typeof ScrollAreaPrimitive.ScrollAreaScrollbar
  > & {
    orientation?: OrientationType
  }
>(({ orientation = 'vertical', ...props }, ref) => (
  <ScrollAreaPrimitive.ScrollAreaScrollbar
    ref={ref}
    orientation={orientation}
    css={[
      tw`flex touch-none select-none transition-colors`,
      ORIENTATION_MAP[orientation],
    ]}
    {...props}
  >
    <ScrollAreaPrimitive.ScrollAreaThumb tw="relative flex-1 rounded-full bg-slate-300 dark:bg-slate-700" />
  </ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName

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

const _ScrollArea = ScrollArea
export {
  _ScrollArea as ScrollArea,
  ScrollBar,
  ORIENTATION_MAP as SCROLL_ORIENTATION_MAP,
  type OrientationType as ScrollOrientationType,
}
