'use client'

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

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

export function SectionRenderer({ node, selectedNodeId, onSelectNode }: SectionRendererProps) {
  const [hovered, setHovered] = useState(false)
  const isSelected = selectedNodeId === node.id

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

  const backgroundStyle: React.CSSProperties = {}
  if (node.settings.background) {
    backgroundStyle.backgroundColor = node.settings.background
  }
  if (node.settings.backgroundImage) {
    backgroundStyle.backgroundImage = `url(${node.settings.backgroundImage})`
    backgroundStyle.backgroundSize = 'cover'
    backgroundStyle.backgroundPosition = 'center'
  }
  if (node.settings.backgroundGradient) {
    backgroundStyle.backgroundImage = node.settings.backgroundGradient
  }
  if (node.settings.paddingTop) {
    backgroundStyle.paddingTop = node.settings.paddingTop
  }
  if (node.settings.paddingBottom) {
    backgroundStyle.paddingBottom = node.settings.paddingBottom
  }
  if (node.settings.marginTop) {
    backgroundStyle.marginTop = node.settings.marginTop
  }
  if (node.settings.marginBottom) {
    backgroundStyle.marginBottom = node.settings.marginBottom
  }

  return (
    <div
      data-node-id={node.id}
      className={`relative w-full transition-shadow ${
        isSelected ? 'ring-primary ring-2 ring-offset-2' : hovered ? 'ring-primary/50 ring-1' : ''
      }`}
      style={backgroundStyle}
      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">
          Section
        </span>
      )}

      {node.children.map((child) => {
        if (child.type === 'container') {
          return (
            <ContainerRenderer
              key={child.id}
              node={child}
              selectedNodeId={selectedNodeId}
              onSelectNode={onSelectNode}
            />
          )
        }
        if (child.type === 'row') {
          return (
            <RowRenderer
              key={child.id}
              node={child}
              selectedNodeId={selectedNodeId}
              onSelectNode={onSelectNode}
            />
          )
        }
        return null
      })}
    </div>
  )
}
