import React, { RefObject, useCallback } from 'react';
import { Editor } from 'slate';
import { Room } from 'matrix-js-sdk';
import { Button, Text } from 'folds';
import { resetEditor, resetEditorHistory } from '../../components/editor';
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
import { RoomInput } from '../room/RoomInput';
import * as t from './forumTheme.css';

type ForumReplyComposerProps = {
  editor: Editor;
  room: Room;
  roomId: string;
  threadRootId: string;
  replyToEventId: string;
  fileDropContainerRef: RefObject<HTMLElement>;
  onSent?: () => void;
  onCancel?: () => void;
};

/** Thread reply composer with uploads, emoji, and rich text (same as room messages). */
export function ForumReplyComposer({
  editor,
  room,
  roomId,
  threadRootId,
  replyToEventId,
  fileDropContainerRef,
  onSent,
  onCancel,
}: ForumReplyComposerProps) {
  const powerLevels = usePowerLevels(room);

  const handleMessageSent = useCallback(() => {
    resetEditor(editor);
    resetEditorHistory(editor);
    onSent?.();
  }, [editor, onSent]);
  return (
    <div className={t.ForumFeedReplyForm}>
      <PowerLevelsContextProvider value={powerLevels}>
        <RoomInput
          room={room}
          roomId={roomId}
          editor={editor}
          threadRootId={threadRootId}
          threadReplyToEventId={replyToEventId}
          hideReplyThreadIndicator
          fileDropContainerRef={fileDropContainerRef}
          onMessageSent={handleMessageSent}
        />
      </PowerLevelsContextProvider>
      {onCancel && (
        <div className={t.ForumReplyFormActions}>
          <Button type="button" variant="SurfaceVariant" size="300" onClick={onCancel}>
            <Text size="B400">Cancel</Text>
          </Button>
        </div>
      )}
    </div>
  );
}
