import { useState, useRef, KeyboardEvent } from "react";
import { ActionIcon, Group, Textarea, Tooltip } from "@mantine/core";
import { IconSend, IconMarkdown } from "@tabler/icons-react";

export interface ComposerProps {
  disabled?: boolean;
  onSendText: (body: string) => Promise<void>;
  onSendMarkdown: (md: string) => Promise<void>;
}

export default function Composer({ disabled, onSendText, onSendMarkdown }: ComposerProps) {
  const [value, setValue] = useState("");
  const [sending, setSending] = useState(false);
  const [markdownMode, setMarkdownMode] = useState(false);
  const ref = useRef<HTMLTextAreaElement | null>(null);

  async function doSend() {
    const body = value.trim();
    if (!body || disabled || sending) return;
    setSending(true);
    try {
      if (markdownMode) {
        await onSendMarkdown(body);
      } else {
        await onSendText(body);
      }
      setValue("");
      ref.current?.focus();
    } catch (e) {
      // surface via console; toast wiring is centralised in HomeScreen
      console.error("send failed", e);
    } finally {
      setSending(false);
    }
  }

  function onKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      doSend();
    }
  }

  return (
    <Group gap="xs" align="flex-end" p="md" bg="dark.7" wrap="nowrap">
      <Tooltip label={markdownMode ? "Markdown ON" : "Markdown OFF"} withArrow>
        <ActionIcon
          variant={markdownMode ? "filled" : "subtle"}
          color="violet"
          size="lg"
          onClick={() => setMarkdownMode((v) => !v)}
          disabled={disabled}
        >
          <IconMarkdown size={18} />
        </ActionIcon>
      </Tooltip>
      <Textarea
        ref={ref}
        flex={1}
        autosize
        minRows={1}
        maxRows={6}
        radius="md"
        placeholder={
          disabled
            ? "Select a room to start chatting"
            : markdownMode
            ? "Markdown · Enter to send, Shift+Enter newline"
            : "Message · Enter to send, Shift+Enter newline"
        }
        value={value}
        onChange={(e) => setValue(e.currentTarget.value)}
        onKeyDown={onKeyDown}
        disabled={disabled || sending}
      />
      <ActionIcon
        variant="filled"
        color="violet"
        size="lg"
        onClick={doSend}
        loading={sending}
        disabled={disabled || !value.trim()}
      >
        <IconSend size={18} />
      </ActionIcon>
    </Group>
  );
}
