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

const DEFAULT_EMAIL = `Moikka,

Ilmottautuminen saapui perille.`;

const widgets = {
  datetime: DatetimeWidget,
  signup: SignupQuestionsWidget,
  markdownEditor: MarkdownEditorWidget,
};

const buildSchema = (formData: SignupForm) => {
  const date = new Date();
  const currentDatetime = date.toISOString();
  const tomorrowDate = new Date();
  tomorrowDate.setDate(tomorrowDate.getDate() + 1);
  const tomorrowDatetime = tomorrowDate.toISOString();

  const schema = {
    title: formData?.title_fi ?? "New Sign-up form",
    type: "object",
    required: ["title_fi", "title_en", "start_time", "end_time", "questions"],
    properties: {
      title_fi: {
        type: "string",
        title: "Title (FI)",
        default: "",
      },
      title_en: {
        type: "string",
        title: "Title (EN)",
        default: "",
      },
      visible: {
        type: "boolean",
        title: "Visible",
        default: false,
      },
      quota: {
        type: "integer",
        title: "Quota",
        minimum: 0,
        default: 0,
      },
      start_time: {
        type: "string",
        title: "Start time",
        default: currentDatetime,
      },
      end_time: {
        type: "string",
        title: "End time",
        default: tomorrowDatetime,
      },
      email_content: {
        type: "string",
        title: "Email on signup",
        default: DEFAULT_EMAIL,
      },
      questions: {
        type: "string",
        title: "Questions",
        default: "[]",
      },
    },
  };
  return schema;
};

const buildUISchema = () => {
  const uiSchema = {
    email_content: {
      "ui:widget": "markdownEditor",
    },
    start_time: {
      "ui:widget": "datetime",
    },
    end_time: {
      "ui:widget": "datetime",
    },
    questions: {
      "ui:widget": "signup",
    },
  };
  return uiSchema;
};

const SignupCreatePage: NextPage = () => {
  const [formData, setFormData] = useState<SignupForm>(null);
  const [error, setError] = useState<string>(null);

  const router = useRouter();

  let id: string;

  if (router.query?.id && router.query.id !== "create") {
    id = router.query.id as string;
  }

  useEffect(() => {
    const suId = id && Number(id);
    if (suId !== undefined) {
      SignupApi.getForm(suId, true)
        .then((res) => {
          setFormData({
            ...res,
            questions: JSON.stringify(res.questions) as any,
          });
        })
        .catch((err) => setError(err));
    }
  }, [id]);

  const onSubmit = async (data: any) => {
    try {
      const questions = JSON.parse(data.formData.questions);
      const payload: SignupForm = {
        ...data.formData,
        questions,
        schema: buildValidationSchema(questions),
      };

      if (payload.id === undefined) {
        const resp = await SignupApi.createForm(payload);
        toast.success("Sign-up created successfully 😎");
        router.push("/admin/signups");
        setFormData({
          ...resp,
          questions: JSON.stringify(resp.questions) as any,
        });
      } else {
        const resp = await SignupApi.updateForm(payload);
        toast.success("Sign-up updated successfully 😎");
        router.push("/admin/signups");
        setFormData({
          ...resp,
          questions: JSON.stringify(resp.questions) as any,
        });
      }
    } catch (err) {
      toast.error("Uh oh! Something went wrong! Try again later. 😟");
      setError(err);
    }
  };

  const onChange = (data) => setFormData(data.formData);

  const title = formData?.id
    ? `Edit Sign-up Form "${formData.title_fi}"`
    : "Create Sign-up form";

  return (
    <>
      <AdminCreateCommon
        title={title}
        formData={formData}
        schema={buildSchema(formData)}
        UISchema={buildUISchema()}
        onChange={onChange}
        onSubmit={onSubmit}
        error={error}
        widgets={widgets}
      />
      {/* {formData.id && <p>
          Check out the signup form here: <Link to={`/signup/${formData.id}`}>{formData.title_fi}</Link>
        </p>} */}
    </>
  );
};

export default SignupCreatePage;
