import * as React from 'react';
import type { NextPage } from 'next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';
import Link from 'next/link';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2'; // Grid version 2
import Stack from '@mui/material/Stack';
import Divider from '@mui/material/Divider';

import Layout from 'src/components/Layout';
import { Pages } from 'src/constants';
import axios from 'src/lib/axios';
import { ZENDESK_API_URL } from 'src/constants/zendesk';
import SearchInput from 'src/components/Search/HeaderSearch';

import { auth0MetaState } from 'src/atom';
import { useRecoilValue } from 'recoil';

interface ArticlesHomePageProps {
  categories: CategoryItem[];
  sections: SectionItem[];
  articles: ArticleItem[];
}

const ArticlesHomePage: NextPage<ArticlesHomePageProps> = (props) => {
  const auth0Meta = useRecoilValue(auth0MetaState);
  // const zendeskData = useRecoilValue(zendeskDataState);
  const { t } = useTranslation();
  // const router = useRouter();
  // const { id } = router.query;

  return (
    <Layout
      title="Articles"
      description="View general and public articles"
      breadcrumbs={[
        { id: 'home', path: Pages.Home, label: t('pages.home') },
        { id: 'articles', label: t(`articles.title`) },
      ]}
      authType="disabled"
      RightSide={auth0Meta && <SearchInput />}
    >
      <Box>
        {props.categories.map((category) => (
          <Box key={category.id}>
            <Typography variant="h5" component="h2" gutterBottom>
              {category.name}
            </Typography>
            <Typography variant="body2" gutterBottom>
              {category.description}
            </Typography>
            <Divider />
            <Grid container spacing={2}>
              <CategorySection
                category={category}
                sections={props.sections}
                articles={props.articles}
              />
            </Grid>
          </Box>
        ))}
      </Box>
    </Layout>
  );
};

export const CategorySection = ({
  category,
  sections,
  articles,
}: {
  category: CategoryItem;
  sections: SectionItem[];
  articles: ArticleItem[];
}) => {
  const filteredSectionsMemo = React.useMemo(() => {
    return sections.filter((section) => section.category_id === category.id);
  }, [category.id, sections]);

  // return (
  //   <Grid xs={12} sm={6} md={4}>
  //     <Stack
  //       direction="column"
  //       spacing={2}
  //       sx={{
  //         marginTop: '2rem',
  //       }}
  //     >
  //       {filteredSectionsMemo.map((section) => (
  //         <Box key={section.id} width={`fit-content`}>
  //           <Link href={`/articles/sections/${section.id}`}>
  //             <Typography
  //               variant="body2"
  //               component="div"
  //               gutterBottom
  //               sx={{
  //                 width: 'fit-content',
  //               }}
  //             >
  //               {section.name}
  //             </Typography>
  //           </Link>
  //         </Box>
  //       ))}
  //     </Stack>
  //   </Grid>
  // );
  return (
    <>
      {filteredSectionsMemo.map((section) => {
        const filteredArticles = articles.filter(
          (article) => article.section_id === section.id
        );

        if (filteredArticles.length === 0) {
          return null;
        }

        return (
          <Grid key={section.id} xs={12} sm={6} md={4}>
            <Typography
              variant="h6"
              component="div"
              gutterBottom
              sx={{
                width: 'fit-content',
                marginTop: '2rem',
              }}
            >
              {section.name}
            </Typography>

            <Stack
              direction="column"
              spacing={2}
              sx={{
                marginTop: '2rem',
              }}
            >
              {filteredArticles.map((article) => (
                <Box key={article.id} width={`fit-content`}>
                  <Link
                    href={`/articles/${calcPathnameFromHtmlUrl(
                      article.html_url
                    )}`}
                  >
                    <Typography
                      variant="body2"
                      component="div"
                      gutterBottom
                      sx={{
                        width: 'fit-content',
                      }}
                    >
                      {article.name}
                    </Typography>
                  </Link>
                </Box>
              ))}
            </Stack>
          </Grid>
        );
      })}
    </>
  );
};

export interface CategoryItem {
  id: number;
  name: string;
  description: string;
  locale: string;
  position: number;
  html_url: string;
  outdated: boolean;
  [key: string]: any;
}

export interface SectionItem {
  id: number;
  category_id: number;
  name: string;
  description: string;
  locale: string;
  position: number;
  html_url: string;
  outdated: boolean;
  [key: string]: any;
}

export interface ArticleItem {
  id: number;
  section_id: number;
  name: string;
  title: string;
  locale: string;
  position: number;
  html_url: string;
  outdated: boolean;
  [key: string]: any;
}

export async function getArticles(): Promise<{
  articles: ArticleItem[];
  count: number;
  next_page: number | null;
  previous_page: number | null;
  page: number;
  per_page: number;
  page_count: number;
  sort_order: string;
  sort_by: string;
}> {
  const data = await axios
    .get(`${ZENDESK_API_URL}/help_center/articles`, {
      headers: {
        Authorization: `Bearer ${process.env.ZENDESK_END_USER_TOKEN}`,
      },
    })
    .then((res) => res.data);
  return data;
}

export async function getCategories(): Promise<{
  categories: CategoryItem[];
  count: number;
  next_page: number | null;
  previous_page: number | null;
  page: number;
  per_page: number;
  page_count: number;
  sort_order: string;
  sort_by: string;
}> {
  const data = await axios
    .get(`${ZENDESK_API_URL}/help_center/categories`, {
      headers: {
        Authorization: `Bearer ${process.env.ZENDESK_END_USER_TOKEN}`,
      },
    })
    .then((res) => res.data);
  return data;
}

export async function getSections(categoryID: string | number): Promise<{
  sections: SectionItem[];
  count: number;
  next_page: number | null;
  previous_page: number | null;
  page: number;
  per_page: number;
  page_count: number;
  sort_order: string;
  sort_by: string;
}> {
  const data = await axios
    .get(`${ZENDESK_API_URL}/help_center/categories/${categoryID}/sections`, {
      headers: {
        Authorization: `Bearer ${process.env.ZENDESK_END_USER_TOKEN}`,
      },
    })
    .then((res) => res.data);
  return data;
}

export async function getArticleDetail(
  articleId: string | number
): Promise<{ article: ArticleItem }> {
  const data = await axios
    .get(`${ZENDESK_API_URL}/help_center/articles/${articleId}`, {
      headers: {
        Authorization: `Bearer ${process.env.ZENDESK_END_USER_TOKEN}`,
      },
    })
    .then((res) => res.data);
  return data;
}

export function calcPathnameFromHtmlUrl(html_url: string): string {
  const pathname = html_url.split(`/`).pop() || html_url;
  return pathname;
}

export async function getStaticProps({ locale }: any) {
  if (process.env.SKIP_BUILD_STATIC_GENERATION) {
    return {
      props: {
        categories: [],
        sections: [],
        articles: [],
        ...(await serverSideTranslations(locale, ['common'])),
        // Will be passed to the page component as props
      },
    };
  }
  const data = await getCategories();
  const categories =
    process.env.NODE_ENV === 'development'
      ? data.categories
      : data.categories.filter((i) => i.id === 360003289394); // only show "General" category
  const sections = [];
  for (const category of categories) {
    const sectionsData = await getSections(category.id);
    sections.push(...sectionsData?.sections);
  }
  const articles = [];
  const articlesData = await getArticles();
  articles.push(...articlesData?.articles);
  // print categories & sections & articles
  console.log(
    `building ${categories.length} categories`,
    categories.map((a) => a.title),
    `building ${sections.length} sections`,
    sections.map((a) => a.title),
    `building ${articles.length} articles`,
    articles.map((a) => a.title)
  );
  return {
    props: {
      categories,
      sections,
      articles,
      ...(await serverSideTranslations(locale, ['common'])),
      // Will be passed to the page component as props
    },
  };
}

export default ArticlesHomePage;
