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';
import { ProductDataDB } from '../utils/interface/productInterface';

interface Props {
  data: { featuredProducts: ProductDataDB[], message: string };
}

const Home: NextPage<Props> = ({ data }) => {
  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={data.featuredProducts}
        ></FeaturedProductsList>
        <Features />
        <CompanyInfo />
      </Box>
    </>
  )
}

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

export default Home
