import { getIsProduction } from '@websolutespa/bom-core';
import { useMetaData } from '@websolutespa/bom-mixer-hooks';
import { IMetaData } from '@websolutespa/bom-mixer-models';
import Head from 'next/head';
import { ReactNode } from 'react';
import { TwitterCard } from '../meta-data/twitter-card';

const USE_KEYWORDS = false;

export function Meta({
  children,
  ...props
}: {
  children?: ReactNode,
  indexable?: boolean | ((metaData: IMetaData) => boolean);
}) {
  const metaData = useMetaData();
  const { brand, meta } = metaData;
  const { title, description, keywords, robots, canonical, alternates, xDefault } = meta;
  const isIndexable = (): boolean => {
    if (
      props.indexable === false ||
      (
        typeof props.indexable === 'function' &&
        props.indexable(metaData) === false
      )
    ) {
      return false;
    }
    return getIsProduction();
  };
  return (
    <>
      <Head>
        <title>{title}</title>
        <meta name="description" content={description} />
        {USE_KEYWORDS && keywords && (
          <meta name="keywords" content={keywords} />
        )}
        {isIndexable() ? (
          <meta name="robots" content={robots || 'index, follow'} />
        ) : (
          <meta name="robots" content="noindex, nofollow" />
        )}
        {canonical && (
          <link rel="canonical" href={canonical} />
        )}
        {alternates.map((alternate) => (
          <link key={alternate.id} rel="alternate" href={alternate.href} hrefLang={alternate.hrefLang} />
        ))}
        {xDefault && (
          <link rel="alternate" href={xDefault.href} hrefLang="x-default" />
        )}
      </Head>
      {children ? (
        <Head>{children}</Head>
      ) : (
        <>
          <Head>
            <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
            <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
            <link rel="shortcut icon" href="/favicon.ico" />
            <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
            <link rel="manifest" href="/site.webmanifest" />
            <meta name="apple-mobile-web-app-title" content={brand.appName} />
          </Head>
          <TwitterCard />
        </>
      )}
    </>
  );
}
