import { useNavigate } from "@solidjs/router";
import { JSXElement, Show, createSignal, onMount, useContext } from "solid-js";

import { LoginContext } from "../Context/GlobalState";
import { NewPost, createPost } from "../Util/api";

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

  // We assumte this context is always available
  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("/");
      });
    }
  };

  // Bail out if not logged in
  onMount(() => {
    if (!login_ctx.loggedIn()) nav("/");
  });

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