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 "../globalContext";
import { useNavigate, useParams } from "react-router-dom";
import { AuthContext, tokenExpireError } from "../authContext";
import SunEditor, { buttonList } from "suneditor-react";
import "suneditor/dist/css/suneditor.min.css";

let sdk = new MkdSDK();

const EditAdminEmailPage = () => {
  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 editor = React.useRef();
  const [html, setHtml] = useState(null);

  const getSunEditorInstance = (sunEditor) => {
    editor.current = sunEditor;
  };

  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: "emails",
      },
    });

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

  const onSubmit = async (data) => {
    try {
      if (!html) {
        setError("html", {
          type: "manual",
          message: "Email body is required",
        });
        return;
      }

      const payload = {
        id,
        slug,
        subject: data.subject,
        html: html,
        tag: data.tag,
      };

      const result = await sdk.callRestAPI(payload, "PUT");

      if (!result.error) {
        showToast(globalDispatch, "Email updated successfully");
        navigate("/admin/emails");
      } 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) {
      setError("html", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
  };

  return (
    <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
      <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
        {/* Header Section */}
        <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
          <h3 className="text-xl font-medium text-white">Edit Email</h3>
        </div>

        {/* Form Section */}
        <form className="p-4 md:p-6 2xl:p-10" onSubmit={handleSubmit(onSubmit)}>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            {/* Email Type */}
            <div className="md:col-span-2">
              <label className="mb-2.5 block font-medium text-white">
                Email Type (slug)
              </label>
              <input
                type="text"
                placeholder="Email Type"
                value={slug}
                readOnly
                className="w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
              />
            </div>

            {/* Subject */}
            <div className="md:col-span-2">
              <label className="mb-2.5 block font-medium text-white">
                Subject
              </label>
              <input
                type="text"
                placeholder="Subject"
                {...register("subject")}
                className={`w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                  errors.subject?.message ? "border-danger" : ""
                }`}
              />
              {errors.subject?.message && (
                <p className="mt-1 text-sm text-danger">
                  {errors.subject.message}
                </p>
              )}
            </div>

            {/* Tags */}
            <div className="md:col-span-2">
              <label className="mb-2.5 block font-medium text-white">
                Tags
              </label>
              <input
                type="text"
                placeholder="Tags"
                {...register("tag")}
                className={`w-full rounded border-[1.5px] border-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                  errors.tag?.message ? "border-danger" : ""
                }`}
              />
              {errors.tag?.message && (
                <p className="mt-1 text-sm text-danger">{errors.tag.message}</p>
              )}
            </div>

            {/* Email Body */}
            <div className="md:col-span-2">
              <label className="mb-2.5 block font-medium text-white">
                Email Body
              </label>
              <SunEditor
                width="100%"
                height="220px"
                onChange={(newContent) => {
                  setValue("html", newContent);
                  setHtml(newContent);
                }}
                getSunEditorInstance={getSunEditorInstance}
                setOptions={{ buttonList: buttonList.complex }}
              />
              {errors.html?.message && (
                <p className="mt-1 text-sm text-danger">
                  {errors.html.message}
                </p>
              )}
            </div>
          </div>

          {/* Form Actions */}
          <div className="mt-6 flex items-center gap-4">
            <button
              type="submit"
              className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
            >
              Update
            </button>
            <button
              type="button"
              onClick={() => navigate(-1)}
              className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-7 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
            >
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default EditAdminEmailPage;
