import { useEffect } from "react";
import { NextPage, GetServerSideProps, GetServerSidePropsContext } from "next";
import { useRouter } from "next/router";
import { getSession } from "next-auth/react";
import Head from "next/head";
import Link from "next/link";
import ReactMarkdown from "react-markdown";
import { Grid, Button } from "@mui/material";
import { useTranslate } from "react-polyglot";
import { useCookies } from "react-cookie";
import { Layout } from "components/Layout";
import { getUserVisualizations } from "lib/opensearch";
import { Welcome } from "components/Welcome";
import { WelcomeDialog } from "components/WelcomeDialog";
import { VisualizationCard } from "components/VisualizationCard";
import { useAppContext } from "components/AppProvider";

type MyVisualizationsProps = {
  visualizations: any;
};

const MyVisualizations: NextPage<MyVisualizationsProps> = ({
  visualizations,
}) => {
  const router = useRouter();
  const cookieName = "homeIntroComplete";
  const [cookies, setCookie] = useCookies([cookieName]);
  const t = useTranslate();
  const {
    colors: { white, leafcutterElectricBlue },
    typography: { h4 },
  } = useAppContext();
  const homeIntroComplete = parseInt(cookies[cookieName], 10) || 0;

  useEffect(() => {
    if (homeIntroComplete === 0) {
      setCookie(cookieName, `${1}`, { path: "/" });
      router.push(`${router.pathname}?tooltip=welcome`);
    }
  }, [homeIntroComplete, router, setCookie]);

  return (
    <Layout>
      <Head>
        <title>Digital Threat Dashboard – Leafcutter</title>
      </Head>
      <Welcome />
      <Grid
        container
        spacing={3}
        sx={{ pt: "22px", pb: "22px" }}
        direction="row-reverse"
      >
        <Link href="/create" passHref>
          <Button
            sx={{
              fontSize: 14,
              borderRadius: 500,
              color: leafcutterElectricBlue,
              border: `2px solid ${leafcutterElectricBlue}`,
              fontWeight: "bold",
              textTransform: "uppercase",
              pl: 6,
              pr: 5,
              ":hover": {
                backgroundColor: leafcutterElectricBlue,
                color: white,
                opacity: 0.8,
              },
            }}
          >
            {t("createVisualization")}
          </Button>
        </Link>
      </Grid>
      <Grid
        container
        direction="row"
        wrap="wrap"
        spacing={3}
        justifyContent="space-between"
      >
        {visualizations.length === 0 ? (
          <Grid
            container
            sx={{ height: 300, width: "100%", pt: 10 }}
            justifyContent="center"
          >
            <Grid item sx={{ ...h4, width: 450, textAlign: "center" }}>
              <ReactMarkdown>{t("noSavedVisualizations")}</ReactMarkdown>
            </Grid>
          </Grid>
        ) : null}
        {visualizations.map((visualization: any, index: number) => (
          <VisualizationCard
            id={visualization.id}
            key={index}
            title={visualization.title}
            description={visualization.description}
            url={visualization.url}
          />
        ))}
      </Grid>
      <WelcomeDialog />
    </Layout>
  );
};

export default MyVisualizations;

export const getServerSideProps: GetServerSideProps = async (
  context: GetServerSidePropsContext
) => {
  const session = (await getSession(context)) ?? null;
  const visualizations = await getUserVisualizations(
    session?.user?.email ?? "none",
    20
  );
  return { props: { visualizations } };
};
