'use client';

import React, { useRef } from 'react';
import { clearFormatting, toggleBold, toggleBullets, toggleItalic, toggleUnderline } from './richText';
import RichPreview, { shortcutOf } from './RichPreview';

interface Props {
  value: string;
  onChange: (v: string) => void;
  disabled?: boolean;
  rows?: number;
}

export default function RichTextArea({ value, onChange, disabled, rows = 8 }: Props) {
  const ref = useRef<HTMLTextAreaElement>(null);

  const apply = (fn: typeof toggleBold) => {
    const el = ref.current;
    if (!el) return;
    const r = fn(value, el.selectionStart, el.selectionEnd);
    onChange(r.text);
    requestAnimationFrame(() => {
      el.focus();
      el.setSelectionRange(r.start, r.end);
    });
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
        <button type="button" className="rb-btn rb-btn-sm" disabled={disabled}
          onMouseDown={(e) => e.preventDefault()} onClick={() => apply(toggleBold)} title="Bold (Ctrl+B) — **text**">
          <b>B</b>
        </button>
        <button type="button" className="rb-btn rb-btn-sm" disabled={disabled}
          onMouseDown={(e) => e.preventDefault()} onClick={() => apply(toggleItalic)} title="Italic (Ctrl+I) — *text*">
          <i style={{ fontFamily: 'Georgia, serif' }}>I</i>
        </button>
        <button type="button" className="rb-btn rb-btn-sm" disabled={disabled}
          onMouseDown={(e) => e.preventDefault()} onClick={() => apply(toggleUnderline)} title="Underline (Ctrl+U) — __text__">
          <u>U</u>
        </button>
        <button type="button" className="rb-btn rb-btn-sm" disabled={disabled}
          onMouseDown={(e) => e.preventDefault()} onClick={() => apply(toggleBullets)} title="Bullet list">
          • List
        </button>
        <button type="button" className="rb-btn rb-btn-sm" disabled={disabled}
          onMouseDown={(e) => e.preventDefault()} onClick={() => apply(clearFormatting)} title="Remove bold / italic / underline from the selected text (or all text when nothing is selected)">
          Clear format
        </button>
        <span style={{ alignSelf: 'center', fontSize: 11, color: '#9ca3af' }}>Select words, then B / I / U (or Ctrl+B / Ctrl+I / Ctrl+U)</span>
      </div>
      <textarea ref={ref} className="rb-textarea" rows={rows} disabled={disabled}
        value={value} onChange={(e) => onChange(e.target.value)}
        onKeyDown={(e) => {
          const k = shortcutOf(e);
          if (!k || disabled) return;
          e.preventDefault();
          apply(k === 'bold' ? toggleBold : k === 'italic' ? toggleItalic : toggleUnderline);
        }} />
      <RichPreview text={value} />
    </div>
  );
}