import axios from "axios";
import delve from "dlv";

import SeoConfig from "../../components/seo-config/seo-config";
import Layout from "../../components/layout/layout";
import Categories from "../../components/categories/categories";

import styles from "./index.module.scss";
import BlogSearch from "../../components/blog-search/blog-search";
import {environment} from "../../environments/environment";
import CardBlog from "../../components/card-blog/card-blog";
import BlogPagination from "../../components/blog-pagination/blog-pagination";

export async function getServerSideProps(context) {
  const {query} = context;

  let postsUrl = `${environment.strapiApiUrl}/articles?populate=deep&sort=publishedAt:DESC`;
  if (query && query.page) {
    postsUrl += `$pagination[page]=${query.page}`;
  }

  const categories = await axios.get(`${environment.strapiApiUrl}/categories?populate=deep`);
  const posts = await axios.get(postsUrl);
  return {
    props: {
      categories: delve(categories, 'data.data', []),
      lastPublished: delve(posts, 'data.data', []),
      paginator: delve(posts, 'data.meta', []),
    }
  }
}

export function Blog({menuHeader, menuFooter, seo, categories, lastPublished, paginator}) {
  return (
    <>
      <SeoConfig {...seo}/>
      <Layout menuHeader={menuHeader} menuFooter={menuFooter} headerTransparent={true}>
        <main className={styles['blog-container'] + " w-full my-4 px-2 lg:px-0"}>
          <section className="container max-w-screen-xl mx-auto relative flex flex-col md:flex-row">
            <section className="grow md:basis-4/6 mx-2 md:mx-0 md:pr-5">
              {lastPublished.map((post, index: number) => (
                <CardBlog key={'card-blog-' + post.id + index} item={post}/>))
              }

              {lastPublished.length > 0 && (<footer className="mt-10">
                <BlogPagination paginator={paginator}/>
              </footer>)}
            </section>
            <aside className="grow md:basis-2/6">
              <BlogSearch/>
              <Categories items={categories}/>
            </aside>
          </section>
        </main>
      </Layout>
    </>
  );
}

export default Blog;
