import { Card, Textarea } from "@mantine/core";
import { useState } from "react";
import { useTRPCClient } from "../trpc-client";

export default function ChatPage() {
  const [inputMessage, setInputMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [outputMessage, setOutputMessage] = useState("");
  const trpc = useTRPCClient();

  async function handleSendMessage() {
    setLoading(true);

    const subscription = trpc.chat.streamMessage.subscribe(
      {
        message: inputMessage,
      },
      {
        onData(value) {
          setOutputMessage((prevOutputMessage) => prevOutputMessage + value);
        },
        onError(error) {
          console.error(error);
        },
        onComplete() {
          subscription.unsubscribe();
          setLoading(false);
        },
      }
    );
  }
  return (
    <div>
      <Card>{outputMessage}</Card>
      <Textarea
        resize="vertical"
        placeholder="Type your message here..."
        value={inputMessage}
        disabled={loading}
        onChange={(e) => setInputMessage(e.target.value)}
        onKeyDown={async (e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            handleSendMessage();
          }
        }}
      />
    </div>
  );
}
