import { GetServerSideProps } from "next";
import { MainLayout } from "../../layouts/MainLayout";
import { BlogPost, getAllFilesFrontMatter } from "../../utils/markdown";
import { FrontMatter } from "../../types/types";
import Link from "next/link";

interface BasicBlogProps extends FrontMatter {
  title: string;
  description: string;
  date: string;
  author: string;
}

const BlogCard = ({ blog, slug }: { blog: BasicBlogProps; slug: string }) => {
  const format = (date: string) => {
    const [day, month, year] = date.split(".");
    const d = new Date(`${year}-${month}-${day}`);
    return d.toLocaleDateString("en-US", {
      month: "long",
      day: "numeric",
      year: "numeric",
    });
  };
  return (
    <div className="p-4 rounded-md border border-gray-700">
      <div className="text-sm font-medium text-gray-500">
        {format(blog.date)}
      </div>
      <h2 className="text-2xl font-bold">{blog.title}</h2>
      <p className="text-gray-400 text-lg">{blog.description}</p>
      <Link href={`blog/${slug}`}>
        <button className="bg-action px-2 py-1 rounded-md mt-4 hover:bg-action/60 transition-all ease-in duration-100 font-bold text-white">
          Read more
        </button>
      </Link>
    </div>
  );
};

const Blog = ({ posts }: { posts: BlogPost[] }) => {
  return (
    <MainLayout>
      <h1 className="text-3xl font-bold mt-10">Blog</h1>
      <div className="w-full h-0.5 bg-white/50 my-4 rounded-full" />
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {posts.map((post, index) => (
          <BlogCard
            key={index}
            blog={post.frontMatter as BasicBlogProps}
            slug={post.slug}
          />
        ))}
      </div>
    </MainLayout>
  );
};

export const getServerSideProps: GetServerSideProps = async () => {
  const posts = getAllFilesFrontMatter();
  return {
    props: {
      posts,
    },
  };
};

export default Blog;
