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

import { LoginContext } from "../../Context/GlobalState";
import { RemovePostIcon } from "../../Util/Icons";
import { deletePost } from "../../Util/api";

export default function RemovePostButton(props: {
  postId: string;
}): JSXElement {
  const navigate = useNavigate();
  const login_ctx = useContext(LoginContext)!;

  // Function to handle post deletion
  const handleDeletePost = async (): Promise<void> => {
    try {
      const response = await deletePost(props.postId, login_ctx.token());
      if (response.ok) {
        // If deletion is successful, navigate to "/" or remount the component
        console.log("Post deleted successfully");
        navigate("/"); // Redirect to "/" after successful deletion
      } else {
        // If deletion fails, handle the error
        console.error("Failed to delete post:", response.statusText);
        // You may want to show an error message or handle the failure in some other way
      }
    } catch (error) {
      console.error("Error deleting post:", error);
      // Handle any unexpected errors that occur during the deletion process
    }
  };

  return (
    <div class="flex p-1">
      <button
        class="rounded-base btn btn-xs hover:border-primary"
        aria-label="Remove post"
        onClick={handleDeletePost}
      >
        <RemovePostIcon />
      </button>
    </div>
  );
}
