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

import {environment} from "../../environments/environment";
import SeoConfig from "../../components/seo-config/seo-config";
import Layout from "../../components/layout/layout";
import CardBlog from "../../components/card-blog/card-blog";
import BlogSearch from "../../components/blog-search/blog-search";
import Categories from "../../components/categories/categories";
import styles from './index.module.scss';
import {useSelector} from "react-redux";
import {selectBlogSearchState} from "../../store/blogSearchSlice";


export async function getServerSideProps(context) {
  const categories = await axios.get(`${environment.strapiApiUrl}/categories?populate=deep`)
  const posts = await axios.get(`${environment.strapiApiUrl}/articles?populate=deep&_sort=date:DESC`)
  return {
    props: {
      categories: delve(categories, 'data.data', []),
      lastPublished: delve(posts, 'data.data', []),
    }
  }
}

export function Search({menuHeader, menuFooter, seo, categories, lastPublished}) {
  const {results} = useSelector(selectBlogSearchState);
  return (
    <>
      <SeoConfig {...seo} />
      <Layout menuHeader={menuHeader}
              menuFooter={menuFooter}
              headerTransparent={true}>
        <main className={styles['blog-container'] + " w-full lg:my-10"}>
          <section className="container max-w-screen-xl mx-auto relative flex">
            <section className="grow lg:basis-4/6 mx-2 lg:mx-0 lg:pr-5">
              <h3 className="text-2xl font-bold mb-5">Résultats de la recherche</h3>
              {Array.isArray(results) && results.length === 0 && (<p>Il n'y a aucun résultat.</p>)}
              {Array.isArray(results) && results.length > 0 && results.map((post: any, index: number) => (
                <CardBlog key={'card-blog-' + post.id + index}
                          item={{
                            attributes: {
                              ...post,
                              image: {
                                data: {
                                  attributes: {...post.image}
                                }
                              },
                              category: {
                                data: {
                                  attributes: {...post.category}
                                }
                              }
                            }
                          }} />))
              }
            </section>
            <aside className="grow lg:basis-2/6">
              <BlogSearch />
              <Categories items={categories} />
            </aside>
          </section>
        </main>
      </Layout>
    </>
  );
}

export default Search;
