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

import { CheckMark, loadSpinner } from "../Util/Icons";
import { PublicComment, getComments } from "../Util/api";

//exported into primary  as a Route
export function Comment({ postId }: { postId: string }): JSXElement {
  const [comments, setComments] = createSignal([] as PublicComment[]);
  const [loading, setLoading] = createSignal(true);

  getComments(postId, 10, 0).then((comment) => {
    setComments(comment);
    setLoading(false);
  });

  return (
    <Show when={!loading()} fallback={loadSpinner()}>
      <For each={comments()}>
        {(comment): JSXElement => <CommentSegment comment={comment} />}
      </For>
    </Show>
  );
}

export function CommentSegment(props: { comment: PublicComment }): JSXElement {
  const nav = useNavigate();
  return (
    <div class="card compact w-full flex-grow border-b-2 border-b-base-300 bg-base-200 text-base-content transition-all hover:bg-base-300">
      <div class="card-body">
        <p class="break-words text-base-content md:px-6 md:pt-2">
          {props.comment?.content}
        </p>
        <div class="card-actions justify-end">
          <button
            onClick={(): void =>
              nav("/comments?post_id" + props.comment?.parent_comment_id)
            }
            class="btn btn-xs"
          >
            <CheckMark />
          </button>
        </div>
      </div>
    </div>
  );
}
