import SendIcon from "@mui/icons-material/Send";
import { IconButton, TextField } from "@mui/material";
import React, { type FormEvent } from "react";
import { MatrixApiEvent } from "../../api/matrix/MatrixApiEvent";
import type { Room } from "../../api/matrix/MatrixApiRoom";
import { useAlert } from "../../hooks/contexts_provider/AlertDialogProvider";
import { useLoadingMessage } from "../../hooks/contexts_provider/LoadingMessageProvider";

export function SendMessageForm(p: { room: Room }): React.ReactElement {
  const loadingMessage = useLoadingMessage();
  const alert = useAlert();

  const [text, setText] = React.useState("");

  const handleTextSubmit = async (e: FormEvent) => {
    e.preventDefault();

    if (text === "") return;

    loadingMessage.show("Sending message...");

    try {
      await MatrixApiEvent.SendTextMessage(p.room, text);

      setText("");
    } catch (e) {
      console.error(`Failed to send message! ${e}`);
      alert(`Failed to send message! ${e}`);
    } finally {
      loadingMessage.hide();
    }
  };

  return (
    <form onSubmit={handleTextSubmit}>
      <div
        style={{
          padding: "10px",
          paddingLeft: "20px",
          display: "flex",
          flexDirection: "row",
        }}
      >
        <TextField
          placeholder="Send a message..."
          variant="standard"
          fullWidth
          style={{}}
          slotProps={{ input: { disableUnderline: true } }}
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
        <IconButton
          size="small"
          style={{ visibility: text === "" ? "hidden" : "visible" }}
          onClick={handleTextSubmit}
        >
          <SendIcon />
        </IconButton>
      </div>
    </form>
  );
}
