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 { GlobalContext, showToast } from "Context/Global";
import { tokenExpireError } from "Src/authContext";
const AddAdminEmailPage = () => {
  const [isUpdating, setIsUpdating] = React.useState(false);

  const schema = yup
    .object({
      slug: yup.string().required(),
      subject: yup.string().required(),
      html: yup.string().required(),
      tag: yup.string().required(),
    })
    .required();

  const { dispatch } = React.useContext(GlobalContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const onSubmit = async (data) => {
    let sdk = new MkdSDK();
    setIsUpdating(true);
    try {
      sdk.setTable("email");

      const result = await sdk.callRestAPI(
        {
          slug: data.slug,
          subject: data.subject,
          html: data.html,
          tag: data.tag,
        },
        "POST"
      );
      if (!result.error) {
        navigate("/admin/email");
        showToast(globalDispatch, "Added");
      } 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("subject", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
    setIsUpdating(false);
  };

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

  return (
    <div className="mx-auto  rounded">
      <div
        className={`flex items-center justify-between gap-4 border-b border-b-[#E0E0E0] p-3`}
      >
        <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">Add Email</span>
        </div>
        <div className="flex items-center gap-4">
          <button
            className="flex items-center rounded-md border border-[#C6C6C6] px-3 py-2 shadow-sm hover:bg-[#F4F4F4]"
            onClick={() => setSidebar(false)}
          >
            Cancel
          </button>
          <button
            className="flex items-center rounded-md bg-[#1f1d1a] px-3 py-2 text-white shadow-sm"
            onClick={async () => {
              await handleSubmit(onSubmit)();
              setSidebar(false);
            }}
            disabled={isUpdating}
          >
            {isUpdating ? "Saving..." : "Save"}
          </button>
        </div>
      </div>
      {/* <h4 className="md:text-xl font-medium text-[16px]">Add Email</h4> */}
      <form
        className=" w-full max-w-lg p-4 text-left"
        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"
            {...register("slug")}
            className={`focus:shadow-outline } w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow
focus:outline-none`}
          />
        </div>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="subject"
          >
            Subject
          </label>
          <input
            type="text"
            placeholder="subject"
            {...register("subject")}
            className={`focus: shadow-outline w-[100px] appearance-none rounded border border-[#1f1d1a] bg-transparent px-3 py-2 leading-tight text-[#1d1f1a] shadow   focus:outline-none sm:w-[180px] ${
              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 max-w-[500px] appearance-none rounded border border-[#1f1d1a] bg-transparent px-3 py-2 text-sm font-normal   leading-tight text-[#1d1f1a] 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 border-[#1f1d1a] px-3 py-2 leading-tight text-gray-700   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 AddAdminEmailPage;
