import React, { useEffect, useState } from "react";
import { NextPage } from "next";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import AdminCreateCommon from "@views/admin/AdminCreateCommon";
import MarkdownEditorWidget from "@components/Widgets/MarkdownEditorWidget";
import { SignupForm } from "@models/Signup";
import SignupApi from "@api/signupApi";

const widgets = {
  markdownEditor: MarkdownEditorWidget,
};

const buildSchema = (title: string) => ({
  title,
  type: "object",
  required: ["subject", "content", "mode"],
  properties: {
    subject: {
      type: "string",
      title: "Title",
      default: "",
    },
    content: {
      type: "string",
      title: "Content",
      default: "",
    },
    mode: {
      type: "string",
      title: "Send to",
      enum: [
        "all",
        "actual",
        "reserved",
      ],
      default: "all",
    },
  },
});

const buildUISchema = () => ({
  content: {
    "ui:widget": "markdownEditor",
  },
});

const useInitializeData = (id: string) => {
  const [signupForm, setSignupForm] = useState<SignupForm>(null);
  useEffect(() => {
    const formId = Number(id);
    if (formId !== undefined) {
      SignupApi.getForm(formId, true)
        .then((res) => setSignupForm(res));
    }
  }, [id]);

  return signupForm;
};

const SignupEmailPage: NextPage = () => {
  const router = useRouter();
  const { id } = router.query;
  const signupForm = useInitializeData(id as string);

  const [error, setError] = useState<string>(null);

  const onSubmit = async (data) => {
    try {
      const payload = data.formData;
      await SignupApi.signupFormSendEmail(payload, Number(id));
      toast.success("Email sent successfully 😎");
    } catch (err) {
      setError(err);
      toast.error("Uh oh! Something went wrong! Try again later. 😟");
    }
  };

  const title = signupForm ? signupForm.title_fi : "Loading...";

  return (
    <AdminCreateCommon
      title={title}
      schema={buildSchema(title)}
      UISchema={buildUISchema()}
      onSubmit={onSubmit}
      error={error}
      widgets={widgets}
    />
  );
};

export default SignupEmailPage;
