import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import BlogPageSection from "../sections/blogs/BlogPageSection"; // Import BlogPageSection
import blogData from "../data/blogdata"; // Import blog data

const BlogPage = () => {
  const { slug } = useParams(); // Extract slug from the route
  const navigate = useNavigate(); // For redirecting if there's an error
  const [post, setPost] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Validate the slug to ensure it's an integer
    if (!/^\d+$/.test(slug)) {
      setError("Invalid blog slug. Redirecting...");
      setTimeout(() => navigate("/error"), 2000); // Redirect to an error page or home
      return;
    }

    // Find the blog post based on the slug
    const foundPost = blogData.find((item) => item.id === parseInt(slug, 10));
    if (!foundPost) {
      setError("Blog post not found. Redirecting...");
      setTimeout(() => navigate("/blogs"), 2000); // Redirect if not found
    } else {
      setPost(foundPost);
    }
  }, [slug, navigate]);

  // Display error message if any
  if (error) return <div>{error}</div>;

  // If no post data, return a "Not Found" message
  if (!post) {
    return <div>Loading...</div>;
  }

  // Render the blog post content
  return (
    <div>
      <BlogPageSection post={post} /> {/* Pass the post data to BlogPageSection */}
    </div>
  );
};

export default BlogPage;