import { JSXElement, Show, createSignal, onMount, useContext } from "solid-js";
import { createPost } from "./api";
import { NewPost } from "./api";
import { useNavigate } from "@solidjs/router";
import { LoginContext } from "./Root";

export function NewPostInputArea(): JSXElement {
  const [content, setContent] = createSignal("");
  const [waiting, setWaiting] = createSignal(false);
  const login_ctx = useContext(LoginContext);

  const nav = useNavigate();

  const sendPost = (): void => {
    setWaiting(true);

    const response = createPost({
      content: content(),
      token: login_ctx?.token(),
    } as NewPost);

    if (response) {
      response.then(() => {
        setWaiting(false);
        setContent("");
        nav("/");
      });
    }
  };

  onMount(() => {
    if (login_ctx?.token() == "") nav("/");
  });

  return (
    <Show
      when={!waiting()}
      fallback={
        <span class="loading loading-spinner loading-lg self-center"></span>
      }
    >
      <div class="flex flex-col w-full space-y-2">
        <textarea
          class="textarea textarea-bordered h-32"
          placeholder="Speak your mind..."
          maxLength={500}
          oninput={(input): void => {
            setContent(input.target.value);
          }}
        ></textarea>
        <button
          class={
            "btn btn-primary self-end btn-sm" +
            (content() == "" ? " btn-disabled" : "")
          }
          onclick={sendPost}
        >
          Submit
        </button>
      </div>
    </Show>
  );
}
