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

interface PostListProps {
  posts: {
    id: string;
    title: string;
    content: string;
    shared: boolean;
    hasPassword?: boolean;
  }[];
  readOnly?: 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-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-4 pb-4 overflow-auto">
      {props.posts.map((post) => (
        <div
          className="w-full border border-gray-200 dark:border-gray-700 dark:bg-gray-800 rounded box-border relative p-4 text-base flex flex-col"
          key={post.id}
        >
          <div className="flex items-center justify-between mb-2">
            <span className="font-medium line-clamp-1">
              <a href={`/${post.id}`}>{post.title || "Untitled"}</a>
            </span>
            <div className="flex items-center gap-1 shrink-0">
              {!props.readOnly && post.shared && (
                <i className="bi bi-share-fill text-gray-500 dark:text-gray-400 text-sm" />
              )}
              {post.hasPassword && (
                <i className="bi bi-lock-fill text-gray-500 dark:text-gray-400 text-sm" />
              )}
            </div>
          </div>
          <p className="mb-2 line-clamp-2">
            {post.content || "No content"}
          </p>
          {!props.readOnly && (
            <div className="flex gap-2 mt-auto">
              <Button
                type="button"
                onClick={() => {
                  onEdit(post.id);
                }}
              >
                Edit
              </Button>
              <Button
                type="button"
                variant="danger-outline"
                onClick={() => {
                  onDelete(post.id, post.title);
                }}
              >
                Delete
              </Button>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
