import { useParams, Outlet } from "react-router";
import { posts } from "../lib/post";
import { Link } from "react-router";
import { ContentState, convertFromRaw, Editor, EditorState } from "draft-js";
import { useState } from "react";
import { useNavigate } from "react-router";

export function BlogPostDetail({
  deletePost,
}: {
  deletePost: (id: number) => void;
}) {
  const { postId } = useParams();
  const post = posts.find((post) => post.id === parseInt(postId!));
  const [editorState, setEditorState] = useState(() => {
    try {
      const data = JSON.parse(`"${post?.content ?? ""}"`);
      return EditorState.createWithContent(convertFromRaw(data));
    } catch {
      console.log("fallback");
      return EditorState.createWithContent(
        ContentState.createFromText(post?.content ?? ""),
      );
    }
  });
  const navigate = useNavigate();

  if (!post) {
    return <div>Post not found</div>;
  }

  const formattedDate = new Date(post.datePosted).toLocaleDateString("en-US", {
    month: "long",
    day: "numeric",
    year: "numeric",
  });

  return (
    <>
      <title>{post.title}</title>
      <div className="md:grid md:grid-cols-3 flex flex-col w-full">
        <Link
          to="/"
          className="text-gray-700 dark:text-gray-200 hover:text-gray-400 flex justify-center items-center w-16 mb-4 md:mb-0"
        >
          Home
        </Link>
        <h1 className="text-3xl md:text-4xl font-bold text-center mb-4 md:mb-0">
          {post.title}
        </h1>
        <div className="flex md:justify-end items-center">
          <Link to={`/post?postId=${post.id}`} className="w-1/3">
            <div className="bg-blue-500 hover:bg-blue-700 text-white w-full font-bold py-2 px-4 rounded cursor-pointer text-center">
              Edit Post
            </div>
          </Link>
        </div>
      </div>
      <div className="flex flex-col gap-1 md:gap-2.5 justify-center items-center mb-1.5 md:mb-2.5">
        <p className="text-gray-700 dark:text-gray-400 text-sm md:text-lg">
          By: {post.author}
        </p>
        <p className="text-gray-600 dark:text-gray-500 text-xs md:text-base">
          Published on {formattedDate}
        </p>
      </div>
      <div className="text-sm md:text-lg md:w-3xl w-full md:mb-10">
        <Editor
          editorState={editorState}
          onChange={setEditorState}
          readOnly={true}
        />
      </div>
      <button
        className="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded cursor-pointer w-full md:w-3xl"
        onClick={() => {
          if (window.confirm("Are you sure you want to delete this post?")) {
            deletePost(post.id);
            navigate("/");
          }
        }}
      >
        Delete
      </button>
    </>
  );
}

export function PostLayout() {
  return (
    <div className="flex flex-col justify-center gap-3.5 md:gap-5 items-center p-5 w-screen">
      <Outlet />
    </div>
  );
}
