'use client'

import { forwardRef, useRef, useEffect, type HTMLAttributes, type ReactNode } from 'react'
import { cn } from './utils'

export interface ChatDrawerProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  open: boolean
  onClose: () => void
  title: string
  icon?: ReactNode
  messages: ReactNode
  input: ReactNode
  width?: string
}

const ChatDrawer = forwardRef<HTMLDivElement, ChatDrawerProps>(
  ({ open, onClose, title, icon, messages, input, width = '500px', className, ...props }, ref) => {
    const scrollRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
      if (open && scrollRef.current) {
        scrollRef.current.scrollTop = scrollRef.current.scrollHeight
      }
    }, [open, messages])

    useEffect(() => {
      if (!open) return
      const handleEsc = (e: KeyboardEvent) => {
        if (e.key === 'Escape') onClose()
      }
      document.addEventListener('keydown', handleEsc)
      return () => document.removeEventListener('keydown', handleEsc)
    }, [open, onClose])

    return (
      <>
        {open && (
          <div
            className="fixed inset-0 z-40 bg-black/40 backdrop-blur-sm"
            onClick={onClose}
            aria-hidden="true"
          />
        )}
        {open && (
          <div
            ref={ref}
            role="dialog"
            aria-modal={true}
            aria-label={title}
            className={cn(
              'fixed inset-y-0 right-0 z-50 flex flex-col border-l border-border-glass bg-background shadow-xl',
              className
            )}
            style={{ width }}
            {...props}
          >
            <div className="flex shrink-0 items-center gap-3 border-b border-border-glass px-4 py-3">
              {icon && (
                <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/15 text-[hsl(var(--primary))] [&>svg]:size-4">
                  {icon}
                </div>
              )}
              <h2 className="flex-1 text-sm font-semibold text-foreground">{title}</h2>
              <button
                type="button"
                onClick={onClose}
                className="flex h-8 w-8 items-center justify-center rounded-lg text-foreground-tertiary transition-colors hover:bg-foreground/[0.06] hover:text-foreground"
                aria-label="Close"
              >
                <svg
                  className="h-4 w-4"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  aria-hidden="true"
                >
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">
              {messages}
            </div>
            <div className="shrink-0 border-t border-border-glass px-4 py-3">{input}</div>
          </div>
        )}
      </>
    )
  }
)
ChatDrawer.displayName = 'ChatDrawer'
export { ChatDrawer }
