'use client'

import { useState } from 'react'
import type { ColumnNode } from '@actuate-media/cms-core'
import { BlockRenderer } from './BlockRenderer.js'
import { ContainerRenderer } from './ContainerRenderer.js'

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

export function ColumnRenderer({ node, selectedNodeId, onSelectNode }: ColumnRendererProps) {
  const [hovered, setHovered] = useState(false)
  const isSelected = selectedNodeId === node.id
  const width = node.settings.width
  const isEmpty = node.children.length === 0

  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' : ''
      }`}
      style={{
        gridColumn: `span ${width}`,
        padding: node.settings.padding,
        background: node.settings.background,
      }}
      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">
          Col {width}
        </span>
      )}

      {isEmpty ? (
        <div className="border-border text-muted-foreground flex min-h-[64px] items-center justify-center rounded-md border-2 border-dashed text-sm">
          Empty column
        </div>
      ) : (
        <div className="flex flex-col gap-2">
          {node.children.map((child) => {
            if (child.type === 'block') {
              return (
                <BlockRenderer
                  key={child.id}
                  node={child}
                  selectedNodeId={selectedNodeId}
                  onSelectNode={onSelectNode}
                />
              )
            }
            if (child.type === 'container') {
              return (
                <ContainerRenderer
                  key={child.id}
                  node={child}
                  selectedNodeId={selectedNodeId}
                  onSelectNode={onSelectNode}
                />
              )
            }
            return null
          })}
        </div>
      )}
    </div>
  )
}
