import { JSXElement, Show, createSignal, For } from "solid-js";
import { getPosts } from "./api";
import { Post } from "./api";
import { useNavigate } from "@solidjs/router";
import { Arrow } from "./Icons";
import { loadSpinner } from "./Icons";

export function Posts(): JSXElement {
  const [posts, setPosts] = createSignal([] as Post[]);
  const [loading, setLoading] = createSignal(true);

  getPosts().then((posts) => {
    setPosts(posts);
    setLoading(false);
  });

  return (
    <Show when={!loading()} fallback={loadSpinner()}>
      <For each={posts()}>
        {(post): JSXElement => <PostSegment post={post}></PostSegment>}
      </For>
    </Show>
  );
}

// This is the card container for a post
export function PostSegment({ post }: { post: Post }): JSXElement {
  const nav = useNavigate();
  return (
    <div class="card border-b-2 flex-grow border-b-base-300 bg-base-200 hover:bg-base-300 transition-all compact text-base-content w-full">
      <div class="card-body">
        <p class="text-base-content break-words">{post?.content}</p>
        <div class="card-actions justify-end">
          <button
            onClick={(): void => nav("/post/" + post?.id)}
            class="btn btn-xs"
          >
            <Arrow />
          </button>
        </div>
      </div>
    </div>
  );
}
