import * as React from 'react';
import type { NextPage } from 'next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';
import { useRouter } from 'next/router';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import 'github-markdown-css/github-markdown-light.css';

import Layout from 'src/components/Layout';
import { Pages } from 'src/constants';

import {
  getArticles,
  getArticleDetail,
  ArticleItem,
  calcPathnameFromHtmlUrl,
} from 'pages/articles';

interface ArticleDetailPageProps {
  post: { article: ArticleItem };
}

const RequestDetailsPage: NextPage<ArticleDetailPageProps> = (
  props: ArticleDetailPageProps
) => {
  const {
    post: { article },
  } = props;

  const { t } = useTranslation();

  return (
    <Layout
      title="Request Details"
      description="View and manage your requests"
      breadcrumbs={[
        { id: 'home', path: Pages.Home, label: t('pages.home') },
        { id: 'articles', path: Pages.Articles, label: t(`articles.title`) },
        { id: 'article-details', label: `${article.name}` },
      ]}
      authType="disabled"
    >
      <Box
        sx={{
          '& .markdown-body': {
            backgroundColor: 'transparent',
          },
        }}
      >
        <Typography variant="h5" component="h2" gutterBottom>
          {article.title}
        </Typography>
        <Typography variant="body2" gutterBottom>
          {new Date(article.updated_at).toLocaleDateString()}
        </Typography>
        <Box
          className="markdown-body"
          sx={{
            pt: '2rem',
            pb: '2rem',
            maxWidth: '900px',
          }}
        >
          {article.body && (
            <div
              dangerouslySetInnerHTML={{ __html: props.post.article.body }}
            />
          )}
        </Box>
      </Box>
    </Layout>
  );
};

export async function getStaticPaths({ locales }: { locales: string[] }) {
  // When this is true (in preview environments) don't
  // prerender any static pages
  // (faster builds, but slower initial page load)
  if (process.env.SKIP_BUILD_STATIC_GENERATION) {
    return {
      paths: [],
      fallback: 'blocking',
    };
  }

  const articles = [];
  const articlesData = await getArticles();
  articles.push(...articlesData?.articles);
  // print out the articles
  console.log(
    `building ${articles.length} articles`,
    articles.map((a) => a.title)
  );

  const paths: {
    params: { id: string };
    locale?: string;
  }[] = [];
  for (let i = 0; i < articles.length; i++) {
    const article = articles[i];
    for (let j = 0; j < locales.length; j++) {
      const locale = locales[j];
      paths.push({
        params: {
          id: calcPathnameFromHtmlUrl(article.html_url),
        },
        locale,
      });
    }
  }
  return {
    paths,
    fallback: false, // can also be true or 'blocking'
  };
}

// `getStaticPaths` requires using `getStaticProps`
export async function getStaticProps(context: any) {
  const articleId = context.params.id;
  const articleData = await getArticleDetail(articleId);
  return {
    // Passed to the page component as props
    props: {
      post: articleData,
      ...(await serverSideTranslations(context.locale, ['common'])),
    },
  };
}

export default RequestDetailsPage;
