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

import { Arrow, EngagementIcon, loadSpinner } from "../Util/Icons";
import { Post, getPosts } from "../Util/api";

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} />}
      </For>
    </Show>
  );
}

// This is the card container for a post
export function PostSegment({ post } : { post: Post }): JSXElement {
  const nav = useNavigate();

  return (
    <div class="card compact w-full flex-grow border-b-2 border-b-primary bg-base-200 text-base-content transition-all hover:bg-base-300">
      <div class="card-body md:mx-6">
        <h3>
          {post.createdAt ?? "No Creation Date"}
        </h3>
        <p class="break-words text-base-content md:pt-2">
          {post.content}
        </p>
        <div class="card-actions justify-between">
          <button
            // onClick={(engagement)}
            class="btn btn-xs hover:border-x-primary"
            aria-label="Show sign of engagement"
          >
            <EngagementIcon />
          </button>
          <button
            onClick={(): void => nav("/post/" + post.id)}
            class="btn btn-xs"
            aria-label="View post"
          >
            <Arrow />
          </button>
        </div>
      </div>
    </div>
  );
}
