

  
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 "Context/Auth";

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 [isEditing, setIsEditing] = useState(false);
  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: 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);
      }
    })();
  }, []);

  const onSubmit = async (data) => {
    setIsEditing(true);
    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);
    }
    setIsEditing(true);
  };

  return (
    <div className="mx-auto rounded">
      {/* <h4 className="text-lg font-semibold text-left px-4">Edit Email</h4> */}
      <div className={`flex items-center p-3 gap-4 border-b border-b-[#E0E0E0] justify-between`}>
        <div className="flex items-center gap-3">
         {/*  <svg onClick={() => setSidebar(false)} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M14.3322 5.83203L19.8751 11.3749C20.2656 11.7654 20.2656 12.3986 19.8751 12.7891L14.3322 18.332M19.3322 12.082H3.83218" stroke="#A8A8A8" stroke-width="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg> */}
          <span className="text-lg font-semibold">Edit Email</span>
        </div>
        <div className="flex items-center gap-4">
          <button className="flex items-center py-2 px-3 border border-[#C6C6C6] rounded-md shadow-sm hover:bg-[#F4F4F4]" onClick={() => setSidebar(false)}>Cancel</button>
          <button className="flex items-center py-2 px-3 text-white bg-[#4F46E5] rounded-md shadow-sm"
            onClick={async () => {
              await (handleSubmit(onSubmit))()
              setSidebar(false)
            }}
            disabled={isEditing}
          >{isEditing ? "Saving..." : "Save"}</button>
        </div>
      </div>
      <form className="w-full p-4 text-left">
        <div className="mb-4">
          <label
            className="block text-gray-700 text-sm font-bold mb-2"
            htmlFor="slug"
          >
            Email Type
          </label>
          <input
            type="text"
            placeholder="Email Type"
            value={slug}
            readOnly
            className={`shadow appearance-none border  rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline}`}
          />
        </div>
        <div className="mb-4">
          <label
            className="block text-gray-700 text-sm font-bold mb-2"
            htmlFor="email"
          >
            Subject
          </label>
          <input
            type="text"
            placeholder="subject"
            {...register("subject")}
            className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${errors.subject?.message ? "border-red-500" : ""}`}
          />
          <p className="text-red-500 text-xs italic">
            {errors.subject?.message}
          </p>
        </div>
        <div className="mb-4">
          <label
            className="block text-gray-700 text-sm font-bold mb-2"
            htmlFor="tag"
          >
            Tags
          </label>
          <input
            type="text"
            placeholder="tag"
            {...register("tag")}
            className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${errors.tag?.message ? "border-red-500" : ""}`}
          />
          <p className="text-red-500 text-xs italic">{errors.tag?.message}</p>
        </div>
        <div className="mb-4">
          <label
            className="block text-gray-700 text-sm font-bold mb-2"
            htmlFor="html"
          >
            Email Body
          </label>
          <textarea
            placeholder="Email Body"
            className={`shadow appearance-none border  rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline ${errors.html?.message ? "border-red-500" : ""}`}
            {...register("html")}
            rows={15}
          ></textarea>
          <p className="text-red-500 text-xs italic">{errors.html?.message}</p>
        </div>
        <button
          type="submit"
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
        >
          Submit
        </button>
      </form>
    </div>
  );
};

export default EditAdminEmailPage;

  