import React, { useEffect, useState } from "react";
import { NextPage } from "next";
import { useRouter } from "next/router";
import AdminCreateCommon from "@views/admin/AdminCreateCommon";
import Tag from "@models/Tag";
import TagApi from "@api/tagApi";
import Post from "@models/Feed";
import FeedApi from "@api/feedApi";
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: Post, tags: Tag[]) => {
  const date = new Date();
  const currentDatetime = date.toISOString();

  const schema = {
    title: formData?.title_fi ?? "New Post",
    type: "object",
    required: ["title_fi", "title_en", "description_fi", "description_en", "content_fi", "content_en", "publish_time"],
    properties: {
      tags: {
        type: "array",
        title: "Post tags",
        items: {
          type: "number",
          enum: tags.map((t) => t.id),
          enumNames: tags.map((t) => t.name_fi),
        },
        uniqueItems: true,
        default: [],
      },
      visible: {
        type: "boolean",
        title: "Visible",
        default: true,
      },
      publish_time: {
        type: "string",
        title: "Publish time",
        default: currentDatetime,
      },
      autohide_enabled: {
        type: "boolean",
        title: "Autohide enabled",
        default: false,
      },
      autohide: {
        type: "string",
        title: "Autohide time",
        default: "",
      },
      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: Post) => {
  const uiSchema = {
    content_fi: {
      "ui:widget": "markdownEditor",
    },
    content_en: {
      "ui:widget": "markdownEditor",
    },
    publish_time: {
      "ui:widget": "datetime",
    },
    autohide: {
      "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,
      },
    },
  };
  return uiSchema;
};

const FeedCreatePage: NextPage = () => {
  const [formData, setFormData] = useState<Post>(null);
  const [tags, setTags] = useState<Tag[]>([]);
  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(() => {
    TagApi.getTags()
      .then((res) => setTags(res))
      .catch((err) => setError(err));

    const feedId = id && Number(id);
    if (feedId !== undefined) {
      FeedApi.getPost(feedId, { auth: true })
        .then((res) => setFormData({
          ...res,
          tags: (res.tags).map((inst) => inst.id) as any,
        }))
        .catch((err) => setError(err));
    }
  }, [id]);

  const onSubmit = async (data) => {
    try {
      const payload = data.formData;
      payload.tag_id = payload.tags;
      payload.autohide = payload.autohide || new Date();
      if (payload.id === undefined) {
        const resp = await FeedApi.createPost(payload);
        // resp.tags = resp.tags;
        toast.success("Post created successfully 😎");
        router.push("/admin/feed");
        setFormData(resp);
      } else {
        const resp = await FeedApi.updatePost(payload);
        // resp.tags = resp.tag_id;
        toast.success("Post updated successfully 😎");
        router.push("/admin/feed");
        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 Post "${formData.title_fi}"`
    : "Create Post";

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

export default FeedCreatePage;
