import * as React from 'react'
import { useStaticQuery, graphql } from 'gatsby'

import type { SeoProps } from '../types'

const Seo: React.FC<SeoProps> = ({
  description = '',
  lang = 'en',
  meta = [],
  title = '',
  previewImg
}) => {
  const { site } = useStaticQuery(graphql`
    query {
      site {
        siteMetadata {
          title
          description
          siteUrl
          author {
            name
          }
          social {
            linkedin
          }
        }
      }
    }
  `)

  const author = site.siteMetadata?.author?.name
  const metaDescription = description || site.siteMetadata.description
  const defaultTitle = site.siteMetadata?.title
  const pageTitle = title ? `${title} | ${defaultTitle}` : defaultTitle
  const siteUrl = site.siteMetadata?.siteUrl
  const image = previewImg
    ? `${siteUrl}${previewImg}`
    : `${siteUrl}/img/data-controller.svg`

  const metaTags = (
    [
      { name: 'author', property: 'author', content: author },
      {
        name: 'description',
        property: 'og:description',
        content: metaDescription
      },
      { name: 'image', property: 'og:image', content: image },
      {
        name: `linkedin:site`,
        content: site.siteMetadata?.social?.linkedin || ``
      },
      { name: `twitter:card`, content: `summary` },
      { name: `twitter:description`, content: metaDescription },
      { name: `twitter:title`, content: title },
      { property: `og:title`, content: title },
      { property: `og:type`, content: `website` }
    ] as Array<{ name?: string; property?: string; content?: string }>
  ).concat(meta)

  return (
    <>
      <html lang={lang} />
      <title>{pageTitle}</title>
      <link
        rel="alternate"
        type="application/rss+xml"
        title={`${defaultTitle} RSS Feed`}
        href={`${siteUrl}rss.xml`}
      />
      {metaTags.map((tag, index) => (
        <meta
          key={tag.name || tag.property || index}
          name={tag.name}
          property={tag.property}
          content={tag.content}
        />
      ))}
    </>
  )
}

export default Seo
