"use client";

import { useEffect, FC } from "react";
import { useRouter, usePathname } from "next/navigation";
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 { Welcome } from "app/_components/Welcome";
import { WelcomeDialog } from "app/_components/WelcomeDialog";
import { VisualizationCard } from "app/_components/VisualizationCard";
import { useAppContext } from "app/_components/AppProvider";

type HomeProps = {
  visualizations: any;
};

export const Home: FC<HomeProps> = ({ visualizations }) => {
  const router = useRouter();
  const pathname = usePathname();
  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(`${pathname}?tooltip=welcome`);
    }
  }, [homeIntroComplete, router, setCookie]);

  return (
    <>
      <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 />
    </>
  );
};
