import React from "react";
import { NextPage, GetStaticProps, GetStaticPaths } from "next";
import Head from "next/head";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import { Signup, SignupForm } from "@models/Signup";
import SignupApi from "@api/signupApi";
import SignUpPageView from "@views/SignUpPage/SignUpPageView";
import PageWrapper from "@views/common/PageWrapper";
import LoadingView from "@views/common/LoadingView";
import noop from "@utils/noop";
import NotFoundPage from "@pages/404";

type InitialProps = {
  form: SignupForm;
};

const SignUpPage: NextPage<InitialProps> = ({ form }) => {
  const router = useRouter();

  if (router.isFallback) {
    return <LoadingView />;
  }

  if (!form) {
    return (
      <NotFoundPage />
    );
  }

  const onSubmit = async (data) => {
    const payload: Signup = {
      signupForm_id: form.id,
      answer: data.formData,
    };

    try {
      await SignupApi.createSignup(payload);
      toast.success("Sign-up submitted successfully 😎");
      router.push(window.location.href); // TODO: Fetch/update signup list, so user sees the signup in the list
    } catch (error) {
      console.error(error);
      toast.error("Uh oh! Sign-up failed! 😟");
    }
  };

  return (
    <>
      <Head>
        <link rel="canonical" href={`${process.env.NEXT_PUBLIC_SITE_URL}/signup/${form.id}`} />
      </Head>
      <PageWrapper>
        <SignUpPageView
          signUpForm={form}
          formData={{}}
          onChange={noop}
          onSubmit={onSubmit}
        />
      </PageWrapper>
    </>
  );
};

export const getStaticPaths: GetStaticPaths = async () => {
  const allForms = await SignupApi.getForms();
  const paths = allForms.map((e: SignupForm) => ({
    params: {
      id: String(e.id),
    },
  }
  ));
  return {
    paths,
    fallback: true,
  };
};

export const getStaticProps: GetStaticProps<InitialProps> = async ({ params }) => {
  const { id } = params;
  let notFound = false;
  let form: SignupForm;
  try {
    form = await SignupApi.getForm(Number(id));
  } catch {
    notFound = true;
  }
  return {
    props: {
      form,
    },
    revalidate: 10,
    notFound,
  };
};

export default SignUpPage;
