import React, { useEffect, useState } from "react";
import { NextPage } from "next";
import { useRouter } from "next/router";
import AdminCreateCommon from "@views/admin/AdminCreateCommon";
import JobAd from "@models/JobAd";
import JobAdApi from "@api/jobAdApi";
import DatetimeWidget from "@components/Widgets/DatetimeWidget";
import SectionDividerWidget from "@components/Widgets/SectionDividerWidget";
import MarkdownEditorWidget from "@components/Widgets/MarkdownEditorWidget";
import { toast } from "react-toastify";

const widgets = {
  datetime: DatetimeWidget,
  section_divider: SectionDividerWidget,
  markdownEditor: MarkdownEditorWidget,
};

const buildSchema = (formData: JobAd) => {
  const monthFromNow = new Date();
  monthFromNow.setDate(new Date().getDate() + 30);

  const schema = {
    title: formData?.title_fi ?? "New Job Ad",
    type: "object",
    required: ["title_fi", "title_en", "description_fi", "description_en", "content_fi", "content_en", "autohide_at", "autohide_enabled", "visible"],
    properties: {
      visible: {
        type: "boolean",
        title: "Visible",
        default: true,
      },
      autohide_enabled: {
        type: "boolean",
        title: "Autohide enabled",
        default: false,
      },
      autohide_at: {
        type: "string",
        title: "Autohide time",
        default: monthFromNow.toISOString(),
      },
      finnish_section_divider: {
        title: "Finnish",
        type: "string",
      },
      title_fi: {
        type: "string",
        title: "Title",
        default: "",
      },
      description_fi: {
        type: "string",
        title: "Description",
        default: "",
      },
      content_fi: {
        type: "string",
        title: "Content",
        default: "",
      },
      english_section_divider: {
        title: "English",
        type: "string",
      },
      title_en: {
        type: "string",
        title: "Title",
        default: "",
      },
      description_en: {
        type: "string",
        title: "Description",
        default: "",
      },
      content_en: {
        type: "string",
        title: "Content",
        default: "",
      },
    },
  };
  return schema;
};

const buildUISchema = (formData: JobAd) => ({
  content_fi: {
    "ui:widget": "markdownEditor",
  },
  content_en: {
    "ui:widget": "markdownEditor",
  },
  autohide_at: {
    "ui:widget": formData && formData.autohide_enabled ? "datetime" : "hidden",
  },
  finnish_section_divider: {
    "ui:widget": "section_divider",
    "ui:options": {
      label: false,
    },
  },
  english_section_divider: {
    "ui:widget": "section_divider",
    "ui:options": {
      label: false,
    },
  },
});

const JobAdCreatePage: NextPage = () => {
  const [formData, setFormData] = useState<JobAd>(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 jobId = id && Number(id);
    if (jobId !== undefined) {
      JobAdApi.getJobAd(jobId, true)
        .then((res) => setFormData(res))
        .catch((err) => setError(err));
    }
  }, [id]);

  const onSubmit = async (data) => {
    try {
      const payload = data.formData;
      if (payload.id === undefined) {
        const resp = await JobAdApi.createJobAd(payload);
        toast.success("Job ad created successfully 😎");
        router.push("/admin/jobads");
        setFormData(resp);
      } else {
        const resp = await JobAdApi.updateJobAd(payload);
        toast.success("Job ad updated successfully 😎");
        router.push("/admin/jobads");
        setFormData(resp);
      }
    } 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 Ad "${formData.title_fi}"`
    : "Create Ad";

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

export default JobAdCreatePage;
