'use client'

import { useState } from 'react'
import type { RowNode } from '@actuate-media/cms-core'
import { ColumnRenderer } from './ColumnRenderer.js'

export interface RowRendererProps {
  node: RowNode
  selectedNodeId: string | null
  onSelectNode: (id: string | null) => void
}

export function RowRenderer({ node, selectedNodeId, onSelectNode }: RowRendererProps) {
  const [hovered, setHovered] = useState(false)
  const isSelected = selectedNodeId === node.id
  const gap = node.settings.gap ?? '16px'
  const verticalAlign = node.settings.verticalAlign ?? 'stretch'

  const alignMap: Record<string, string> = {
    top: 'start',
    center: 'center',
    bottom: 'end',
    stretch: 'stretch',
  }

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    onSelectNode(node.id)
  }

  return (
    <div
      data-node-id={node.id}
      className={`relative transition-shadow ${
        isSelected ? 'ring-primary ring-2 ring-offset-2' : hovered ? 'ring-primary/50 ring-1' : ''
      }`}
      onClick={handleClick}
      onMouseEnter={(e) => {
        e.stopPropagation()
        setHovered(true)
      }}
      onMouseLeave={() => setHovered(false)}
    >
      {(hovered || isSelected) && (
        <span className="bg-primary text-primary-foreground absolute -top-2 -left-1 z-10 rounded px-1.5 py-0.5 text-xs font-medium">
          Row
        </span>
      )}

      <div
        className="grid grid-cols-12"
        style={{
          gap,
          alignItems: alignMap[verticalAlign] ?? 'stretch',
        }}
      >
        {node.children.map((col) => (
          <ColumnRenderer
            key={col.id}
            node={col}
            selectedNodeId={selectedNodeId}
            onSelectNode={onSelectNode}
          />
        ))}
      </div>
    </div>
  )
}
