import { useEffect } from 'react'
import { X } from 'lucide-react'
import { TreeMetadataForm } from './TreeMetadataForm'

interface MetadataSidePanelProps {
  isOpen: boolean
  onClose: () => void
}

export function MetadataSidePanel({ isOpen, onClose }: MetadataSidePanelProps) {
  // Close on Escape key
  useEffect(() => {
    if (!isOpen) return

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [isOpen, onClose])

  if (!isOpen) return null

  return (
    <>
      {/* Backdrop — click to close */}
      <div
        className="fixed inset-0 z-40 bg-background/40 backdrop-blur-sm"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Side panel — slides in from right */}
      <div
        className="fixed right-0 top-0 z-50 flex h-full w-80 flex-col border-l border-border bg-card shadow-xl"
        role="dialog"
        aria-label="Flow metadata"
      >
        {/* Panel header */}
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <h2 className="text-sm font-semibold text-foreground font-heading">
            Flow Details
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="rounded p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
            aria-label="Close metadata panel"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Scrollable metadata form */}
        <div className="flex-1 overflow-y-auto px-4 py-4">
          <TreeMetadataForm />
        </div>
      </div>
    </>
  )
}

export default MetadataSidePanel
