import { useCallback, useEffect, useRef } from 'react'
import { Bold, Italic, List, ListOrdered, Underline } from 'lucide-react'
import styles from './RichTextEditor.module.css'

interface RichTextEditorProps {
  value: string
  onChange: (value: string) => void
  placeholder?: string
  /** Compact editor height for short fields like invoice top text. */
  editorMinHeight?: number
}

export function RichTextEditor({
  value,
  onChange,
  placeholder = '',
  editorMinHeight = 88,
}: RichTextEditorProps) {
  const editorRef = useRef<HTMLDivElement>(null)

  const syncChange = useCallback(() => {
    if (editorRef.current) {
      onChange(editorRef.current.innerHTML)
    }
  }, [onChange])

  useEffect(() => {
    if (editorRef.current && editorRef.current.innerHTML !== value) {
      editorRef.current.innerHTML = value
    }
  }, [value])

  function exec(command: string) {
    editorRef.current?.focus()
    document.execCommand(command)
    syncChange()
  }

  return (
    <div className={styles.wrapper}>
      <div className={styles.toolbar}>
        <button type="button" onClick={() => exec('bold')} title="Bold" aria-label="Bold">
          <Bold size={14} />
        </button>
        <button type="button" onClick={() => exec('italic')} title="Italic" aria-label="Italic">
          <Italic size={14} />
        </button>
        <button
          type="button"
          onClick={() => exec('underline')}
          title="Underline"
          aria-label="Underline"
        >
          <Underline size={14} />
        </button>
        <span className={styles.divider} />
        <button
          type="button"
          onClick={() => exec('insertUnorderedList')}
          title="Bullet list"
          aria-label="Bullet list"
        >
          <List size={14} />
        </button>
        <button
          type="button"
          onClick={() => exec('insertOrderedList')}
          title="Numbered list"
          aria-label="Numbered list"
        >
          <ListOrdered size={14} />
        </button>
      </div>
      <div
        ref={editorRef}
        className={styles.editor}
        style={{ minHeight: editorMinHeight }}
        contentEditable
        role="textbox"
        aria-multiline="true"
        data-placeholder={placeholder}
        onInput={syncChange}
        suppressContentEditableWarning
      />
    </div>
  )
}

/** True when HTML is empty or only whitespace / empty tags. */
export function isEmptyRichText(html: string | null | undefined): boolean {
  return richTextToPlain(html).length === 0
}

/** Strip tags for single-line list previews. */
export function richTextToPlain(html: string | null | undefined): string {
  if (!html) return ''
  return html
    .replace(/<br\s*\/?>/gi, ' ')
    .replace(/&nbsp;/gi, ' ')
    .replace(/<[^>]+>/g, '')
    .replace(/\s+/g, ' ')
    .trim()
}
