import * as React from 'react';
import Link from 'next/link';
import Head from 'next/head';
import allLanguages from './allLanguages.json';
import { withRouter } from 'next/router';

type LayoutProps = {
  title?: string;
  languages?: string[];
  router: any;
};

type LanguageLinkProps = {
  languageFileName: string;
  router: any;
};

const Layout: React.FunctionComponent<LayoutProps> = ({
  children,
  title = 'Flight Translating',
  languages = [],
  router
}) => (
  <div>
    <Head>
      <title>{title}</title>
      <meta charSet="utf-8" />
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    </Head>
    <header>
      <nav className="main-nav">
        <Link href="/">
          <a className={router.asPath === '/' ? 'active' : ''}>All languages</a>
        </Link>
        {languages
          .filter(fileName => fileName !== 'default.json')
          .map(key => (
            <LanguageLink key={key} languageFileName={key} router={router} />
          ))}
      </nav>
    </header>
    {children}
    <style jsx global>
      {`
        body {
          margin: 0;
          padding: 0;
        }
        header {
          overflow: hidden;
          position: fixed;
          top: 0;
          width: 100%;
          background: white;
        }
        nav.main-nav {
          padding: 0 1.5rem;
          margin: 0 -0.5rem;
          border-bottom: 1px solid #a9a1a1;
        }
        nav.main-nav a {
          padding: 1.5rem 0;
          margin: 0 0.75rem;
          display: inline-block;
          text-decoration: none;
          color: #111;
          font-size: 1rem;
          font-family: sans-serif;
          letter-spacing: -0.5px;
        }
        nav.main-nav a.active {
          font-weight: bold;
        }
      `}
    </style>
  </div>
);

const LanguageLink: React.FunctionComponent<LanguageLinkProps> = ({
  languageFileName,
  router
}) => {
  const language = languageFileName.split('.')[0];
  const languageObject = (allLanguages as {
    [key: string]: { name: string; nativeName: string };
  })[language];

  const linkText = !!languageObject
    ? `${languageObject.name.split(',')[0].split(';')[0]} (${language})`
    : language;

  return (
    <Link href="/translations/[lang]" as={`/translations/${language}`}>
      <a
        className={
          router.asPath === `/translations/${language}` ? 'active' : ''
        }
      >
        {linkText}
      </a>
    </Link>
  );
};

export default (withRouter as any)(Layout);
