import React from 'react';
import PropTypes from 'prop-types';

import { schemaGenerator } from '~helpers/schema';
import { getUrl, getPageImage, imagePrettyUrl } from '~helpers/getters';
import keygen from '~helpers/keygen';

export function getLanguage(language) {
  if (language === 'no') return 'nb-NO';
  return language || 'en';
}
export function getCanonicalUrl(page) {
  if (page.canonical_url) {
    return `${process.env.GATSBY_SITE_URL}${page.canonical_url}`;
  }
  if (page.path === '/') {
    return process.env.GATSBY_SITE_URL;
  }
  return `${process.env.GATSBY_SITE_URL}${page.path.replace(/^\//, '')}`;
}
export function getRobotOptions(options) {
  const array = [];
  if (!options.page_index && process.env.GATSBY_ACTIVE_ENV !== 'development') array.push('noindex');
  if (!options.links_followed && process.env.GATSBY_ACTIVE_ENV !== 'development')
    array.push('nofollow');
  if (!options.images_index && process.env.GATSBY_ACTIVE_ENV !== 'development')
    array.push('noimageindex');
  if (!options.show_snippet && process.env.GATSBY_ACTIVE_ENV !== 'development')
    array.push('nosnippet');
  if (process.env.GATSBY_ACTIVE_ENV === 'development') array.push('noindex,follow');
  return array.join();
}

function setName(string) {
  const [name] = string.split('.');
  return name[0].toUpperCase() + name.slice(1);
}

const HeadData = ({ page = {}, siteInfo }) => {
  const pageImage = getPageImage(page) ? getPageImage(page) : imagePrettyUrl(siteInfo?.site_logo);
  let defaultHref = null;
  // When google re-indexes dev NSA and IRL, remove lines 28, 41, 42, 43 and process.env.GATSBY_ACTIVE_ENV !== 'development' from lines 24, 25, 27, 29, 43
  return (
    <>
      <title>{page.meta_title}</title>
      <html lang={getLanguage(page.language)} />
      <meta name="description" content={page.meta_description} />
      {page.meta_robots && process.env.GATSBY_ACTIVE_ENV !== 'development' && (
        <meta name="robots" content={page.meta_robots.join()} />
      )}

      {page.robot_options && <meta name="robots" content={getRobotOptions(page.robot_options)} />}

      {process.env.GATSBY_ACTIVE_ENV === 'development' && (
        <meta name="googlebot" content="noindex,follow" />
      )}
      <link rel="canonical" href={getCanonicalUrl(page)} />
      {page?.hreflangs?.map((link) => {
        if (link?.default) defaultHref = link?.path;
        return <link rel="alternate" href={getUrl(link.path)} hrefLang={link.language} />;
      })}
      {defaultHref && <link rel="alternate" href={getUrl(defaultHref)} hrefLang="x-default" />}

      {page.preconnect_links &&
        page.preconnect_links.map((link) => <link key={keygen()} rel="preconnect" href={link} />)}
      <meta name="og:title" content={page.meta_title} />
      <meta name="og:site_name" content={siteInfo?.site_name && setName(siteInfo?.site_name)} />
      <meta name="og:description" content={page.meta_description} />
      <meta name="og:type" content={page.path === '/' ? 'website' : 'article'} />
      <meta name="og:image" content={pageImage} />
      <meta name="og:url" content={getUrl(page.path)} />
      <meta
        property="og:locale"
        content={getLanguage(page.language) === 'en' ? 'en_GB' : getLanguage(page.language)}
      />

      {schemaGenerator(page, pageImage).map(
        (schema) =>
          schema && (
            <script key={keygen()} type="application/ld+json">
              {`${schema}`}
            </script>
          )
      )}
    </>
  );
};

HeadData.propTypes = {
  siteInfo: PropTypes.shape({
    robots_txt: PropTypes.string,
    site_logo: PropTypes.string,
    site_name: PropTypes.string,
  }),
  page: PropTypes.shape({
    meta_title: PropTypes.string,
    language: PropTypes.string,
    meta_description: PropTypes.string,
    meta_robots: PropTypes.arrayOf(PropTypes.string),
    path: PropTypes.string,
    preconnect_links: PropTypes.arrayOf(PropTypes.string),
  }),
};

export default HeadData;
