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 { GlobalContext, showToast } from "Context/Global";
import { useNavigate, useParams } from "react-router-dom";
import { AuthContext, tokenExpireError } from "Src/authContext";

let sdk = new MkdSDK();

const EditAdminEmailPage = ({ activeId, setSidebar }) => {
  const schema = yup
    .object({
      subject: yup.string().required(),
      html: yup.string().required(),
      tag: yup.string().required(),
    })
    .required();
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const navigate = useNavigate();
  const [id, setId] = useState(0);
  const [slug, setSlug] = useState("");
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const params = useParams();

  useEffect(
    function () {
      globalDispatch({
        type: "SETPATH",
        payload: {
          path: "email",
        },
      });

      (async function () {
        try {
          sdk.setTable("email");
          const result = await sdk.callRestAPI({ id: Number(activeId) }, "GET");
          if (!result.error) {
            setValue("subject", result.model.subject);
            setValue("html", result.model.html);
            setValue("tag", result.model.tag);
            setSlug(result.model.slug);
            setId(result.model.id);
          }
        } catch (error) {
          console.log("error", error);
          tokenExpireError(dispatch, error.message);
        }
      })();
    },
    [activeId]
  );

  const onSubmit = async (data) => {
    try {
      const result = await sdk.callRestAPI(
        { id, slug, subject: data.subject, html: data.html, tag: data.tag },
        "PUT"
      );

      if (!result.error) {
        showToast(globalDispatch, "Updated");
        navigate("/admin/email");
      } 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],
            });
          }
        }
      }
    } catch (error) {
      console.log("Error", error);
      setError("html", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
  };

  return (
    <div className="mx-auto rounded p-5 shadow-md ">
      <h4 className="text-[16px] font-medium md:text-xl">Edit Email</h4>
      <form className="w-full max-w-lg " onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="slug"
          >
            Email Type
          </label>
          <input
            type="text"
            placeholder="Email Type"
            value={slug}
            readOnly
            className={`focus:shadow-outline} mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-[#1f1d1a] shadow focus:outline-none`}
          />
        </div>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="email"
          >
            Subject
          </label>
          <input
            type="text"
            placeholder="subject"
            {...register("subject")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-[#1f1d1a] shadow focus:outline-none ${
              errors.subject?.message ? "border-red-500" : ""
            }`}
          />
          <p className="text-xs italic text-red-500">
            {errors.subject?.message}
          </p>
        </div>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="tag"
          >
            Tags
          </label>
          <input
            type="text"
            placeholder="tag"
            {...register("tag")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-[#1f1d1a] shadow focus:outline-none ${
              errors.tag?.message ? "border-red-500" : ""
            }`}
          />
          <p className="text-xs italic text-red-500">{errors.tag?.message}</p>
        </div>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="html"
          >
            Email Body
          </label>
          <textarea
            placeholder="Email Body"
            className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-[#1f1d1a] shadow focus:outline-none ${
              errors.html?.message ? "border-red-500" : ""
            }`}
            {...register("html")}
            rows={15}
          ></textarea>
          <p className="text-xs italic text-red-500">{errors.html?.message}</p>
        </div>
        <button
          type="submit"
          className="focus:shadow-outline rounded bg-blue-500 px-4 py-2 font-bold text-white hover:bg-blue-700 focus:outline-none"
        >
          Submit
        </button>
      </form>
    </div>
  );
};

export default EditAdminEmailPage;
