import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBold, faItalic, faStrikethrough, faCode, faEyeSlash } from '@fortawesome/free-solid-svg-icons';

interface FormatToolbarProps {
  inputRef: React.RefObject<HTMLTextAreaElement | null>;
  setInput: (updater: (prev: string) => string) => void;
  disabled?: boolean;
}

// ponytail: wraps selected text in input with markdown syntax
function wrap(input: HTMLTextAreaElement, prefix: string, suffix: string, set: (updater: (prev: string) => string) => void) {
  const start = input.selectionStart ?? 0;
  const end = input.selectionEnd ?? 0;
  const value = input.value;
  const selected = value.slice(start, end) || 'text';
  const before = value.slice(0, start);
  const after = value.slice(end);
  set(() => before + prefix + selected + suffix + after);
  // restore cursor after React re-renders
  requestAnimationFrame(() => {
    input.focus();
    input.setSelectionRange(start + prefix.length, start + prefix.length + selected.length);
  });
}

const FORMATS: { icon: any; prefix: string; suffix: string; title: string }[] = [
  { icon: faBold, prefix: '**', suffix: '**', title: 'Bold (Ctrl+B)' },
  { icon: faItalic, prefix: '*', suffix: '*', title: 'Italic (Ctrl+I)' },
  { icon: faStrikethrough, prefix: '~~', suffix: '~~', title: 'Strikethrough' },
  { icon: faCode, prefix: '`', suffix: '`', title: 'Code' },
  { icon: faEyeSlash, prefix: '||', suffix: '||', title: 'Spoiler' },
];

export function FormatToolbar({ inputRef, setInput, disabled }: FormatToolbarProps) {
  return (
    <span className="flex items-center gap-0.5 shrink-0">
      {FORMATS.map((f, i) => (
        <button
          key={i}
          type="button"
          disabled={disabled}
          onClick={() => inputRef.current && wrap(inputRef.current, f.prefix, f.suffix, setInput)}
          title={f.title}
          className="text-gb-fg-f hover:text-gb-orange px-1 py-0.5 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <FontAwesomeIcon icon={f.icon} className="w-3 h-3" />
        </button>
      ))}
    </span>
  );
}
