import type { NextPage } from 'next'
import { useSession } from 'next-auth/react';
import Head from 'next/head'
import { Box } from '@mui/system';
import Hero from '../components/hero/Hero';
import { getFeaturedProducts } from '../requests/products/featuredProductsRequest';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import FeaturedProductsList from '../components/products/featured-products-list/FeaturedPorductsList';
import Features from '../components/features/Features';
import CompanyInfo from '../components/company-info/CompanyInfo';
import { useUserUpdate } from '../store/user-context';
import { getStorage } from '../utils/helpers/storage';
import { useEffect } from 'react';


const Home: NextPage = ({ featuredProducts }) => {
  const { data: session } = useSession();
  const { addUser } = useUserUpdate();

  useEffect(() => {
    const userData = getStorage('user-data');
    if (session?.user && userData.length === 0) {
      addUser(session.user);
    }
  }, [session, addUser]);

  return (
    <>
      <Box sx={{ width: '100%', height: '100%' }}>
        <Head>
          <title>Coffee Shop</title>
          <meta name="description" content="Random data with pagination..." />
        </Head>
        <Hero />
        <FeaturedProductsList
          featuredProducts={featuredProducts}
        ></FeaturedProductsList>
        <Features />
        <CompanyInfo />
      </Box>
    </>
  )
}

export async function getStaticProps({ locale }: any) {
  try {
    const { message, featuredProducts } = await getFeaturedProducts();
    return {
      props: {
        ...(await serverSideTranslations(locale, ["home"])),
        message,
        featuredProducts,
      },
    };
  } catch (error) {
    return {
      props: {
        ...(await serverSideTranslations(locale, ['home'])),
        errorMessage: error,
        featuredProducts: [],
      },
    };
  }
}

export default Home
