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

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

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

  const navigate = useNavigate();

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

  const onSubmit = async (data) => {
    let sdk = new MkdSDK();

    try {
      if (!html) {
        setError("html", {
          type: "manual",
          message: "Email body is required",
        });
        return;
      }

      sdk.setTable("email");

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

      const result = await sdk.callRestAPI(payload, "POST");
      if (!result.error) {
        navigate("/admin/emails");
        showToast(globalDispatch, "Email added successfully");
      } 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("subject", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
  };

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

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

        {/* Form Section */}
        <div className="p-4 md:p-6 2xl:p-10">
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              {/* Email Type */}
              <div>
                <label className="mb-2.5 block text-sm font-medium text-white">
                  Email Type (slug)
                </label>
                <input
                  type="text"
                  placeholder="Email Type"
                  {...register("slug")}
                  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 ${
                    errors.slug?.message ? "border-danger" : ""
                  }`}
                />
                {errors.slug?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.slug.message}
                  </p>
                )}
              </div>

              {/* Subject */}
              <div>
                <label className="mb-2.5 block text-sm 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 ${
                    errors.subject?.message ? "border-danger" : ""
                  }`}
                />
                {errors.subject?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.subject.message}
                  </p>
                )}
              </div>

              {/* Tags */}
              <div>
                <label className="mb-2.5 block text-sm 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 ${
                    errors.tag?.message ? "border-danger" : ""
                  }`}
                />
                {errors.tag?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.tag.message}
                  </p>
                )}
              </div>
            </div>

            {/* Email Body - Full Width */}
            <div className="mt-6">
              <label className="mb-2.5 block text-sm font-medium text-white">
                Email Body
              </label>
              <SunEditor
                width="100%"
                height="220px"
                setContents={content}
                onChange={(content) => {
                  setContent(content);
                  setHtml(content);
                  editor.current.setContents(content);
                }}
                getSunEditorInstance={getSunEditorInstance}
                setOptions={{ buttonList: buttonList.complex }}
              />
              {errors.html?.message && (
                <p className="mt-1 text-sm text-danger">
                  {errors.html.message}
                </p>
              )}
            </div>

            {/* Form Actions */}
            <div className="flex gap-4 items-center mt-6">
              <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"
              >
                Submit
              </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>
    </div>
  );
};

export default AddAdminEmailPage;
