import * as React from 'react'
import { Group, Panel, Separator } from 'react-resizable-panels'
import type { GroupProps, PanelProps, SeparatorProps } from 'react-resizable-panels'
import { cn } from '@/lib/utils'

export interface ResizablePanelGroupProps
  extends Omit<GroupProps, 'orientation'> {
  direction?: 'horizontal' | 'vertical'
  className?: string
}

const ResizablePanelGroup = React.forwardRef<HTMLDivElement, ResizablePanelGroupProps>(
  function ResizablePanelGroup({ direction = 'horizontal', className, ...props }, ref) {
    return (
      <Group
        elementRef={ref}
        orientation={direction}
        className={cn('flex h-full w-full', direction === 'vertical' && 'flex-col', className)}
        {...props}
      />
    )
  }
)
ResizablePanelGroup.displayName = 'ResizablePanelGroup'

export type ResizablePanelProps = PanelProps

const ResizablePanel = React.forwardRef<HTMLDivElement, ResizablePanelProps>(
  function ResizablePanel({ className, ...props }, ref) {
    return <Panel elementRef={ref} className={cn(className)} {...props} />
  }
)
ResizablePanel.displayName = 'ResizablePanel'

export interface ResizableHandleProps extends SeparatorProps {
  withHandle?: boolean
  className?: string
}

const ResizableHandle = React.forwardRef<HTMLDivElement, ResizableHandleProps>(
  function ResizableHandle({ withHandle = false, className, ...props }, ref) {
    return (
      <Separator
        elementRef={ref}
        className={cn(
          'relative flex shrink-0 items-center justify-center bg-border-tertiary',
          'after:absolute after:inset-0 after:transition-colors',
          'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1',
          'data-[resize-handle-active]:bg-border-secondary',
          'aria-[orientation=vertical]:h-full aria-[orientation=vertical]:w-px aria-[orientation=vertical]:cursor-col-resize',
          'aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:cursor-row-resize',
          '[&[aria-orientation=vertical]>div]:h-6 [&[aria-orientation=vertical]>div]:w-1',
          '[&[aria-orientation=horizontal]>div]:h-1 [&[aria-orientation=horizontal]>div]:w-6',
          className
        )}
        {...props}
      >
        {withHandle && (
          <div className="z-10 shrink-0 rounded-lg bg-border-secondary" data-resize-handle />
        )}
      </Separator>
    )
  }
)
ResizableHandle.displayName = 'ResizableHandle'

export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
