import Button from "../components/form/Button.tsx";

interface PostListProps {
  posts: { id: string; title: string; content: string; shared: boolean }[];
}

export default function PostList(props: PostListProps) {
  const onEdit = (id: string) => {
    location.href = `/${id}`;
  };

  const onDelete = (id: string, title: string) => {
    globalThis.$modal?.show(
      "Confirm delete",
      `Are you sure you want to delete ${title}?`,
      [
        {
          text: "Confirm",
          onClick: async () => {
            const resp = await fetch("/api/post", {
              method: "DELETE",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                id,
              }),
            });
            const respJson = await resp.json();
            if (respJson.success) {
              location.reload();
            }
          },
        },
        {
          text: "Cancel",
        },
      ],
    );
  };

  return (
    <div className="w-full grid grid-cols-4 gap-4 mt-4 pb-4 overflow-auto">
      {props.posts.map((post) => (
        <div className="w-full min-w-[180px] border border-gray-200 rounded box-border relative p-4 text-base flex flex-col" key={post.id}>
          <span className="font-medium mb-2">{post.title || "Untitled"}</span>
          <div className="absolute right-4 top-3 text-2xl z-[1]">
            <i
              className="bi bi-x cursor-pointer"
              onClick={() => {
                onDelete(post.id, post.title);
              }}
            />
          </div>
          <span className="overflow-hidden text-ellipsis whitespace-nowrap mb-2">{post.content || "No content"}</span>
          <Button
            type="button"
            onClick={() => {
              onEdit(post.id);
            }}
          >
            Edit
          </Button>
        </div>
      ))}
    </div>
  );
}
