'use client'

import * as React from 'react'
import { TextBlock as TextBlockType } from '../types'

interface TextBlockProps {
  block: TextBlockType
  onChange: (block: TextBlockType) => void
  isEditing?: boolean
  /** Optional custom rich text editor component. Receives content, onChange, placeholder, and className. */
  renderEditor?: (props: {
    content: string
    onChange: (html: string) => void
    placeholder?: string
    className?: string
  }) => React.ReactNode
}

export function TextBlockEditor({ block, onChange, isEditing = true, renderEditor }: TextBlockProps) {
  if (!isEditing) {
    return (
      <div
        className="prose prose-sm max-w-none py-2"
        style={{
          fontSize: block.fontSize ? `${block.fontSize}px` : undefined,
          fontFamily: block.fontFamily || undefined,
          lineHeight: block.lineHeight || undefined,
          color: block.textColor || undefined,
        }}
        dangerouslySetInnerHTML={{ __html: block.content || '<p></p>' }}
      />
    )
  }

  // If a custom editor is provided, use it
  if (renderEditor) {
    return (
      <div
        style={{
          fontSize: block.fontSize ? `${block.fontSize}px` : undefined,
          fontFamily: block.fontFamily || undefined,
          lineHeight: block.lineHeight || undefined,
          color: block.textColor || undefined,
        }}
      >
        {renderEditor({
          content: block.content,
          onChange: (html) => onChange({ ...block, content: html }),
          placeholder: 'Write your content...',
          className: 'min-h-[60px] border-0',
        })}
      </div>
    )
  }

  // Default fallback: simple contentEditable div
  return (
    <div
      style={{
        fontSize: block.fontSize ? `${block.fontSize}px` : undefined,
        fontFamily: block.fontFamily || undefined,
        lineHeight: block.lineHeight || undefined,
        color: block.textColor || undefined,
      }}
    >
      <div
        contentEditable
        suppressContentEditableWarning
        className="min-h-[60px] outline-none prose prose-sm max-w-none py-2"
        dangerouslySetInnerHTML={{ __html: block.content || '' }}
        onBlur={(e) => onChange({ ...block, content: e.currentTarget.innerHTML })}
      />
    </div>
  )
}
