import * as React from 'react'
import { cn } from '@/lib/utils'

export interface MessageScrollerProps extends React.HTMLAttributes<HTMLDivElement> {
  autoScroll?: boolean
}

const MessageScroller = React.forwardRef<HTMLDivElement, MessageScrollerProps>(
  ({ className, autoScroll = false, children, ...props }, ref) => {
    const localRef = React.useRef<HTMLDivElement | null>(null)

    React.useImperativeHandle(ref, () => localRef.current as HTMLDivElement)

    React.useEffect(() => {
      if (!autoScroll || !localRef.current) {
        return
      }

      localRef.current.scrollTop = localRef.current.scrollHeight
    }, [autoScroll, children])

    return (
      <div
        ref={localRef}
        data-slot="message-scroller"
        className={cn('relative h-full overflow-y-auto overscroll-contain scroll-smooth', className)}
        {...props}
      >
        {children}
      </div>
    )
  }
)
MessageScroller.displayName = 'MessageScroller'

export type MessageScrollerContentProps = React.HTMLAttributes<HTMLDivElement>

const MessageScrollerContent = React.forwardRef<HTMLDivElement, MessageScrollerContentProps>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      data-slot="message-scroller-content"
      className={cn('flex min-h-full flex-col gap-4 p-4', className)}
      {...props}
    />
  )
)
MessageScrollerContent.displayName = 'MessageScrollerContent'

export type MessageScrollerButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>

const MessageScrollerButton = React.forwardRef<HTMLButtonElement, MessageScrollerButtonProps>(
  ({ className, type = 'button', ...props }, ref) => (
    <button
      ref={ref}
      type={type}
      data-slot="message-scroller-button"
      className={cn(
        'inline-flex size-8 items-center justify-center rounded-full border border-border bg-bg-elevated text-text-secondary shadow-sm transition-colors',
        'hover:bg-fill-secondary hover:text-text',
        'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base',
        'disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4',
        className
      )}
      {...props}
    />
  )
)
MessageScrollerButton.displayName = 'MessageScrollerButton'

export { MessageScroller, MessageScrollerContent, MessageScrollerButton }
