import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import MkdSDK from "Utils/MkdSDK";
import { useNavigate } from "react-router-dom";
import { tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Context/Global";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { isImage, empty, isVideo, isPdf } from "Utils/utils";
import { MkdInput } from "Components/MkdInput";
import { InteractiveButton } from "Components/InteractiveButton";
import { SkeletonLoader } from "Components/Skeleton";

const AddNotesPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const schema = yup
    .object({
      content: yup.string(),
      type: yup.string(),
      status: yup.string(),
      update_id: yup.string(),
    })
    .required();

  const { dispatch } = React.useContext(GlobalContext);
  const [fileObj, setFileObj] = React.useState({});
  const [isSubmitLoading, setIsSubmitLoading] = React.useState(false);

  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });
  const [pageDetails, setPageDetails] = React.useState([]);

  const getPageDetails = async () => {
    const result = await new TreeSDK()
      .getList("table")
      .catch((e) => console.error(object));
    setPageDetails(result.list);
  };

  const previewImage = (field, target) => {
    let tempFileObj = fileObj;
    tempFileObj[field] = {
      file: target.files[0],
      tempURL: URL.createObjectURL(target.files[0]),
    };
    setFileObj({ ...tempFileObj });
  };

  const onSubmit = async (_data) => {
    let sdk = new MkdSDK();
    setIsSubmitLoading(true);
    try {
      for (let item in fileObj) {
        let formData = new FormData();
        formData.append("file", fileObj[item].file);
        let uploadResult = await sdk.uploadImage(formData);
        _data[item] = uploadResult.url;
      }

      sdk.setTable("notes");

      const result = await sdk.callRestAPI(
        {
          content: _data.content,
          type: _data.type,
          status: _data.status,
          update_id: _data.update_id,
        },
        "POST"
      );
      if (!result.error) {
        showToast(globalDispatch, "Added");
        navigate("/admin/notes");
      } else {
        if (result.validation) {
          const keys = Object.keys(result.validation);
          for (let i = 0; i < keys.length; i++) {
            const field = keys[i];
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
      setIsSubmitLoading(false);
    } catch (error) {
      setIsSubmitLoading(false);
      console.log("Error", error);
      setError("content", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "notes",
      },
    });
  }, []);

  return (
    <div className="p-5 mx-auto rounded shadow-md">
      <h4 className="text-[16px] font-medium md:text-xl">Add Notes</h4>
      <form className="w-full max-w-lg" onSubmit={handleSubmit(onSubmit)}>
        <MkdInput
          type={"text"}
          page={"notes"}
          name={"content"}
          errors={errors}
          label={"Content"}
          placeholder={"Content"}
          register={register}
          className={""}
        />

        <MkdInput
          type={"text"}
          page={"notes"}
          name={"type"}
          errors={errors}
          label={"Type"}
          placeholder={"Type"}
          register={register}
          className={""}
        />

        <MkdInput
          type={"text"}
          page={"notes"}
          name={"status"}
          errors={errors}
          label={"Status"}
          placeholder={"Status"}
          register={register}
          className={""}
        />

        <MkdInput
          type={"text"}
          page={"notes"}
          name={"update_id"}
          errors={errors}
          label={"Update Id"}
          placeholder={"Update Id"}
          register={register}
          className={""}
        />

        <InteractiveButton
          type="submit"
          loading={isSubmitLoading}
          disabled={isSubmitLoading}
          className="px-4 py-2 font-bold text-white rounded focus:shadow-outline bg-primary-black focus:outline-none"
        >
          Submit
        </InteractiveButton>
      </form>
    </div>
  );
};

export default AddNotesPage;
