import { useEffect, useCallback } from 'react'
import { X } from 'lucide-react'
import { cn } from './utils'

export interface SlidePanelProps {
  /** Whether the panel is open */
  open: boolean
  /** Called when the panel should close */
  onClose: () => void
  /** Panel title */
  title?: string
  /** Icon to display next to title */
  icon?: React.ReactNode
  /** Panel content */
  children: React.ReactNode
  /** Side to slide from */
  side?: 'left' | 'right'
  /** Panel width */
  width?: 'sm' | 'md' | 'lg' | 'xl'
  /** Whether to show backdrop */
  showBackdrop?: boolean
  /** Additional class names for the panel */
  className?: string
}

const widthClasses = {
  sm: 'w-64',
  md: 'w-80',
  lg: 'w-96',
  xl: 'w-[480px]',
}

/**
 * SlidePanel
 *
 * A slide-in panel component that can appear from the left or right side of the screen.
 * Includes a backdrop overlay and supports keyboard navigation (Escape to close).
 */
export function SlidePanel({
  open,
  onClose,
  title,
  icon,
  children,
  side = 'left',
  width = 'md',
  showBackdrop = true,
  className,
}: SlidePanelProps) {
  // Handle escape key
  const handleEscape = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === 'Escape' && open) {
        onClose()
      }
    },
    [open, onClose]
  )

  useEffect(() => {
    document.addEventListener('keydown', handleEscape)
    return () => document.removeEventListener('keydown', handleEscape)
  }, [handleEscape])

  // Prevent body scroll when open
  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = ''
    }
    return () => {
      document.body.style.overflow = ''
    }
  }, [open])

  const isLeft = side === 'left'

  return (
    <>
      {/* Backdrop */}
      {showBackdrop && (
        <div
          className={cn(
            'fixed inset-0 z-40 bg-black/40 backdrop-blur-sm',
            'transition-opacity duration-300',
            open ? 'opacity-100' : 'pointer-events-none opacity-0'
          )}
          onClick={onClose}
          onKeyDown={e => e.key === 'Enter' && onClose()}
          role="button"
          tabIndex={open ? 0 : -1}
          aria-label="Close panel"
        />
      )}

      {/* Panel */}
      <div
        role="dialog"
        aria-modal="true"
        aria-label={title || 'Side panel'}
        className={cn(
          'fixed inset-y-0 z-50',
          isLeft ? 'left-0' : 'right-0',
          widthClasses[width],
          'bg-background-surface/95 backdrop-blur-xl',
          isLeft ? 'border-r' : 'border-l',
          'border-border-default',
          'transform transition-transform duration-300 ease-out',
          open ? 'translate-x-0' : isLeft ? '-translate-x-full' : 'translate-x-full',
          className
        )}
      >
        {/* Header */}
        {(title || icon) && (
          <div className="border-border-subtle flex items-center justify-between border-b px-5 py-4">
            <div className="flex items-center gap-2">
              {icon && <span className="text-accent-violet">{icon}</span>}
              {title && <h2 className="text-foreground font-semibold">{title}</h2>}
            </div>
            <button
              type="button"
              onClick={onClose}
              className="rounded-lg p-1.5 transition-colors hover:bg-white/5"
              aria-label="Close panel"
            >
              <X className="text-foreground-muted h-4 w-4" />
            </button>
          </div>
        )}

        {/* Content */}
        <div className="max-h-[calc(100vh-80px)] overflow-y-auto">{children}</div>
      </div>
    </>
  )
}
