import React, { useEffect, useState } 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, useParams } from "react-router-dom";
import { AuthContext, 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";

let sdk = new MkdSDK();

const EditNotesPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const schema = yup
    .object({
      content: yup.string(),
      type: yup.string(),
      status: yup.string(),
      update_id: yup.string(),
    })
    .required();
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [fileObj, setFileObj] = React.useState({});
  const [isLoading, setIsLoading] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const navigate = useNavigate();

  const [content, setContent] = useState("");
  const [type, setType] = useState("");
  const [status, setStatus] = useState("");
  const [update_id, setUpdateId] = useState("");
  // const [id, setId] = useState(0);
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const params = useParams();

  useEffect(function () {
    (async function () {
      try {
        setLoading(true);

        sdk.setTable("notes");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        if (!result.error) {
          setValue("content", result.model.content);
          setValue("type", result.model.type);
          setValue("status", result.model.status);
          setValue("update_id", result.model.update_id);

          setContent(result.model.content);
          setType(result.model.type);
          setStatus(result.model.status);
          setUpdateId(result.model.update_id);
          setId(result.model.id);
          setLoading(false);
        }
      } catch (error) {
        setLoading(false);

        console.log("error", error);
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  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) => {
    setIsLoading(true);
    try {
      sdk.setTable("notes");
      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;
      }
      const result = await sdk.callRestAPI(
        {
          id: id,

          content: _data.content,
          type: _data.type,
          status: _data.status,
          update_id: _data.update_id,
        },
        "PUT"
      );

      if (!result.error) {
        showToast(globalDispatch, "Updated");
        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],
            });
          }
        }
      }
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      console.log("Error", error);
      setError("content", {
        type: "manual",
        message: error.message,
      });
    }
  };
  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "notes",
      },
    });
  }, []);

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

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

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

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

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

export default EditNotesPage;
