'use client'; // required if using next 13 app router + client component
import { useEffect, useState } from 'react';
import axios from 'axios';
import Link from 'next/link';

const Blog = () => {
  const [blogs, setBlogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const projectId = "Metatroncubesolution"
  useEffect(() => {
    const fetchBlogs = async () => {
      try {
        const res = await axios.get(
          `http://localhost:3010/api/blog?projectId=${projectId}`
        );
        setBlogs(res.data.blogs);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    if (projectId) fetchBlogs();
  }, [projectId]);

  if (loading) return <p>Loading...</p>;

  return (
    <div className="mt-10">
      <h3 className="mb-6 text-xl font-bold md:text-3xl">Blogs</h3>
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-4">
        {/* Create New Blog */}
        <Link
          href="/create-blog"
          className="flex items-center justify-center space-y-5 rounded-md border border-dashed border-blue-500 bg-blue-50 p-5 text-center shadow hover:bg-blue-100 transition dark:border-blue-800 dark:bg-blue-900 dark:hover:bg-blue-800"
        >
          <div>
            <div className="mb-3 text-5xl text-blue-600 dark:text-white">+</div>
            <h5 className="text-lg font-semibold text-blue-800 dark:text-white">
              Create New Blog
            </h5>
          </div>
        </Link>

        {/* Blog list from API */}
        {blogs.map((blog: any) => (
          <div
            key={blog._id} // backend mongoDB _id
            className="space-y-4 rounded-md border border-white-light bg-white p-5 shadow-[0px_0px_2px_0px_rgba(145,158,171,0.20),0px_12px_24px_-4px_rgba(145,158,171,0.12)] dark:border-[#1B2E4B] dark:bg-black"
          >
            <div className="max-h-56 overflow-hidden rounded-md">
              <img src={blog.imageUrl} alt={blog.title} className="w-full object-cover" />
            </div>

            <h5 className="text-lg font-semibold dark:text-white">{blog.title}</h5>
            <p
              className="text-sm text-gray-600 dark:text-gray-400"
              dangerouslySetInnerHTML={{
                __html:
                  blog.description.replace(/<[^>]+>/g, "").slice(0, 100) +
                  (blog.description.length > 100 ? "..." : ""),
              }}
            />
            <div>
              <Link
                href={`/blog/${blog.slug}`}
                className="inline-block mt-3 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
              >
                Read More
              </Link>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Blog;
