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 ShopAside from "../../components/shop-aside/shop-aside";
import ShopCatalog from "../../components/shop-catalog/shop-catalog";

import styles from './index.module.scss';
import {buildQueriesListFromQueryParams, SortType} from "../../libs/utils";

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

  const queryValues = buildQueriesListFromQueryParams(query);

  let productsUrl = `${environment.strapiApiUrl}/products?populate=deep`;

  if (query && query.page) {
    productsUrl += `$pagination[page]=${query.page}`;
  }

  if (query && query.search) {
    productsUrl += `&filters[$or][0][title][$contains]=${query.search}&filters[$or][1][content][$contains]=${query.search}&filters[$or][2][description][$contains]=${query.search}`;
  }

  if (query && query.sort) {
    if ((query.sort as SortType) === 'pas') {
      productsUrl += `&sort=[amount]:ASC`;
    } else if ((query.sort as SortType) === 'pde') {
      productsUrl += `&sort=[amount]:DESC`;
    } else if ((query.sort as SortType) === 'alp') {
      productsUrl += `&sort=[title]:ASC`;
    } else {
      productsUrl += `&sort=[title]:ASC`;
    }
  }

  if (query && query.facets) {
    const facets: string[] = query.facets.split(':');
    productsUrl += `&filters[amount][$between]=${(parseInt(facets[0], 10) * 100)}&filters[amount][$between]=${(parseInt(facets[1], 10) * 100)}`;
  }

  if (query && query.filters) {
    query.filters.split(',').forEach((filterId, index) => productsUrl += `&filters[filter_items][id][$in][${index}]=${filterId}`);
  }

  let filtersUrl = `${environment.strapiApiUrl}/filter-categories?populate=deep&sort=[filter_section][slug]:DESC`;

  if (query && query.cat) {
    productsUrl += `&filters[filter_items][filter_category][filter_section][slug][$eq]=${query.cat}`;
    filtersUrl += `&filters[filter_section][slug][$eq]=${query.cat}`;
  }

  console.log(productsUrl);

  const sections = await axios.get(`${environment.strapiApiUrl}/filter-sections?populate=deep`);
  const products = await axios.get(productsUrl);
  const filters = await axios.get(filtersUrl);

  return {
    props: {
      sections: delve(sections, 'data.data', []),
      products: delve(products, 'data.data', []),
      filters: delve(filters, 'data.data', []),
      paginator: delve(products, 'data.meta', {pagination: {}}),
      queries: queryValues
    }
  }
}

export function Shop({menuHeader, menuFooter, seo, sections, products, paginator, queries = [], filters = []}) {

  return (
    <>
      <SeoConfig {...seo} />
      <Layout menuHeader={menuHeader}
              menuFooter={menuFooter}
              headerTransparent={true}>
        <main className={styles['blog-container'] + " w-full my-4 lg:px-0"}>
          <section className="container max-w-screen-xl mx-auto relative flex flex-col md:flex-row">
            <aside className="grow md:basis-3/12 md:mx-0 md:pr-5">
              <ShopAside queries={queries}
                         filters={filters}
                         sections={sections} />
            </aside>
            <section className="grow md:basis-9/12 mx-2">
              <ShopCatalog products={products}
                           queries={queries}
                           paginator={paginator} />
            </section>
          </section>
        </main>
      </Layout>
    </>
  );
}

export default Shop;
