
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 { tokenExpireError } from "@/context/Auth";
import { GlobalContext, showToast } from "@/context/Global";
import 'react-quill/dist/quill.snow.css';

const AddSettingPage = ({ setSidebar }) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const schema = yup
    .object({

      setting_key: yup.string(),
      setting_value: yup.string(),
    })
    .required();

  const { dispatch } = React.useContext(GlobalContext);
  const [isUpdating, setIsUpdating] = React.useState(false);
  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("setting");

      const result = await sdk.callRestAPI(
        {

          setting_key: _data.setting_key,
          setting_value: _data.setting_value,
        },
        "POST"
      );
      if (!result.error) {
        showToast(globalDispatch, "Added");
        navigate("/admin/setting");
      } 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("setting_key", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    };
    setIsUpdating(false);
  };

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

  return (
    <div className="rounded  mx-auto">
      <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">Add Setting</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={isUpdating}
          >{isUpdating ? "Saving..." : "Save"}</button>
        </div>
      </div>
      <form className=" w-full max-w-lg p-4 text-left" onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-4  ">
          <label
            className="block text-gray-700 text-sm font-bold mb-2"
            htmlFor="setting_key"
          >
            Setting Key
          </label>
          <input
            placeholder="Setting Key"
            {...register("setting_key")}
            className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${errors.setting_key?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-red-500 text-xs italic">
            {errors.setting_key?.message}
          </p>
        </div>


        <div className="mb-4  ">
          <label
            className="block text-gray-700 text-sm font-bold mb-2"
            htmlFor="setting_value"
          >
            Setting Value
          </label>
          <textarea
            placeholder="Setting Value"
            {...register("setting_value")}
            className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${errors.setting_value?.message ? "border-red-500" : ""
              }`}
            row={15}
          ></textarea>
          <p className="text-red-500 text-xs italic">
            {errors.setting_value?.message}
          </p>
        </div>
      </form>
    </div>
  );
};

export default AddSettingPage;


