import type { GetServerSideProps, NextPage } from 'next';
import HeroCarousel from '../components/HeroCarousel';
import TopProductsSection from '../components/TopProductsSection';
import ProductListing from '../components/ProductListing';
import Seo from '../components/Seo';
import { DEFAULT_DESCRIPTION, HOME_OG_IMAGE, SITE_ALTERNATE_NAMES, SITE_LOGO, SITE_NAME, SITE_URL } from '../lib/seo';
import { fetchFromApi } from '../lib/serverFetch';
import { defaultHeroSlides, type HeroSlide } from '../lib/heroConfig';

interface HomeProps {
  products: any[];
  topProducts: any[];
  reviews: { rating: number }[];
  heroSlides: HeroSlide[];
}

const Home: NextPage<HomeProps> = ({ products, topProducts, reviews, heroSlides }) => {
  const ratingCount = reviews.length;
  const ratingValue = ratingCount
    ? Number((reviews.reduce((sum, review) => sum + review.rating, 0) / ratingCount).toFixed(1))
    : 0;

  const homeJsonLd = {
    '@context': 'https://schema.org',
    '@graph': [
      {
        '@type': ['Organization', 'OnlineStore'],
        '@id': `${SITE_URL}/#organization`,
        name: SITE_NAME,
        alternateName: SITE_ALTERNATE_NAMES,
        url: SITE_URL,
        logo: {
          '@type': 'ImageObject',
          url: SITE_LOGO,
          width: 512,
          height: 512,
        },
        image: SITE_LOGO,
        email: 'info@vystrikejto.cz',
        telephone: '+420605861472',
        currenciesAccepted: 'CZK',
        sameAs: [
          'https://www.instagram.com/vystrikejto/',
          'https://www.tiktok.com/@vystrikejto',
        ],
        ...(ratingCount > 0
          ? {
              aggregateRating: {
                '@type': 'AggregateRating',
                ratingValue,
                reviewCount: ratingCount,
                bestRating: 5,
                worstRating: 1,
              },
            }
          : {}),
      },
      {
        '@type': 'WebSite',
        '@id': `${SITE_URL}/#website`,
        url: SITE_URL,
        name: SITE_NAME,
        alternateName: SITE_ALTERNATE_NAMES,
        inLanguage: 'cs',
        publisher: { '@id': `${SITE_URL}/#organization` },
      },
    ],
  };

  return (
    <>
      <Seo
        title="Celé parfémy | Originální vůně | Vystříkejto.cz"
        description={DEFAULT_DESCRIPTION}
        canonical={`${SITE_URL}/`}
        ogImage={HOME_OG_IMAGE}
        jsonLd={homeJsonLd}
      />
      <HeroCarousel slides={heroSlides} autoPlay={true} autoPlayInterval={5000} />
      <TopProductsSection initialProducts={topProducts} />
      <ProductListing initialProducts={products} />
    </>
  );
};

export const getServerSideProps: GetServerSideProps<HomeProps> = async ({ req }) => {
  const [products, topProducts, reviews, heroResponse] = await Promise.all([
    fetchFromApi<any[]>(req, '/api/products'),
    fetchFromApi<any[]>(req, '/api/top-products'),
    fetchFromApi<{ rating: number }[]>(req, '/api/reviews'),
    fetchFromApi<{ slides: HeroSlide[] }>(req, '/api/hero-slides'),
  ]);

  return {
    props: {
      products: products || [],
      topProducts: topProducts || [],
      reviews: reviews || [],
      heroSlides: heroResponse?.slides?.length
        ? heroResponse.slides
        : defaultHeroSlides.filter((slide) => slide.active),
    },
  };
};

export default Home;
