/* eslint-disable camelcase */
/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import parse from 'html-react-parser';
import PropTypes from 'prop-types';
import { schemaGenerator } from '~helpers/schema';
import { getUrl, getPageImage, imagePrettyUrl } from '~helpers/getters';
import keygen from '~helpers/keygen';
import { getTwitterUsername, transformMetaTitle } from '../../../../helpers/strings';

export function getLanguage(language) {
  if (process.env.GATSBY_SITE_LANG) return process.env.GATSBY_SITE_LANG;
  return language || 'en';
}

export function getLocale(language) {
  if (language) {
    const locale = language.split('_').reverse();
    locale[1] = locale[1].toUpperCase();
    return locale.join('_');
  }
  return null;
}

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 { relation, meta_title, relation_type } = page;
  const pageImage = getPageImage(page) ? getPageImage(page) : imagePrettyUrl(siteInfo?.site_logo);
  const twitterUsername = getTwitterUsername(page.siteSchema?.twitter);
  const parsedMetaDescr = page.meta_description ? parse(page.meta_description) : '';
  const metaTitle = transformMetaTitle(relation, meta_title, relation_type);
  let defaultHref = null;
  const isIL = process.env.GATSBY_SITE_NAME === 'irishluck.ie' && 'en-IE';

  return (
    <>
      <title>{metaTitle}</title>
      <html lang={getLanguage(isIL || page.language)} />
      <meta name="description" content={parsedMetaDescr} />
      {process.env.PLACENAME && <meta name="geo.placename" content={process.env.PLACENAME} />}
      {process.env.COUNTRY && <meta name="geo.region" content={process.env.COUNTRY} />}
      {process.env.ENABLE_PIXEL && (
        <meta name="facebook-domain-verification" content={process.env.FBVERIFACTION} />
      )}
      {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 property="og:title" content={metaTitle} />
      <meta property="og:site_name" content={siteInfo?.site_name && setName(siteInfo?.site_name)} />
      <meta property="og:description" content={parsedMetaDescr} />
      <meta property="og:type" content={page.path === '/' ? 'website' : 'article'} />
      <meta property="og:image" content={pageImage.replace('/filters:format(webp)', '')} />
      <meta property="og:url" content={getUrl(page.path)} />
      <meta property="og:locale" content={getLocale(page.market)} />

      {schemaGenerator(page, pageImage).map(
        (schema) =>
          schema && (
            <script key={keygen()} type="application/ld+json">
              {`${schema}`}
            </script>
          )
      )}
      {twitterUsername && (
        <>
          <meta name="twitter:title" content={metaTitle} />
          <meta name="twitter:description" content={page.meta_description} />
          <meta name="twitter:site" content={`@${twitterUsername}`} />
          <meta name="twitter:creator" content={`@${twitterUsername}`} />
          <meta name="twitter:card" content="summary" />
          <meta name="twitter:image" content={pageImage.replace('/filters:format(webp)', '')} />
          <meta property="twitter:label1" content="Reading time" />
          <meta property="twitter:data1" content={`${page.reading_time}`} />
        </>
      )}
    </>
  );
};

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;
