import React, { 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 { useNavigate, useParams } from "react-router-dom";
import { AuthContext, tokenExpireError } from "@/context/Auth";
import { GlobalContext, showToast } from "@/context/Global";

let sdk = new MkdSDK();

const EditAdminUserPage = ({ activeId, setSidebar }) => {
  const schema = yup
    .object({
      email: yup.string().email().required(),
      password: yup.string(),
      role: yup.string(),
    })
    .required();

  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const navigate = useNavigate();
  const params = useParams();
  const [oldEmail, setOldEmail] = useState("");
  const [id, setId] = useState(0);
  const [isEditing, setIsEditing] = useState(false);

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

  const selectRole = ["admin", "employee"];
  const selectStatus = [
    { key: "0", value: "Inactive" },
    { key: "2", value: "Suspend" },
    { key: "1", value: "Active" },
  ];

  const onSubmit = async (data) => {
    setIsEditing(true);
    try {
      if (oldEmail !== data.email) {
        const emailresult = await sdk.updateEmailByAdmin(data.email, activeId);
        if (!emailresult.error) {
          showToast(globalDispatch, "Email Updated", 1000);
        } else {
          if (emailresult.validation) {
            const keys = Object.keys(emailresult.validation);
            for (let i = 0; i < keys.length; i++) {
              const field = keys[i];
              setError(field, {
                type: "manual",
                message: emailresult.validation[field],
              });
            }
          }
        }
      }

      if (data.password.length > 0) {
        const passwordresult = await sdk.updatePasswordByAdmin(
          data.password,
          activeId
        );
        if (!passwordresult.error) {
          showToast(globalDispatch, "Password Updated", 2000);
        } else {
          if (passwordresult.validation) {
            const keys = Object.keys(passwordresult.validation);
            for (let i = 0; i < keys.length; i++) {
              const field = keys[i];
              setError(field, {
                type: "manual",
                message: passwordresult.validation[field],
              });
            }
          }
        }
      }

      sdk.setTable("user");

      const result = await sdk.callRestAPI(
        { activeId, email: data.email, role: data.role, status: data.status },
        "PUT"
      );

      if (!result.error) {
        showToast(globalDispatch, "Added", 4000);
        navigate("/admin/users");
      } 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("email", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(dispatch, error.message);
    }
    setIsEditing(false);
  };

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

    (async function () {
      try {
        sdk.setTable("user");
        const result = await sdk.callRestAPI({ id: activeId }, "GET");

        if (!result.error) {
          setValue("email", result.model.email);
          setValue("role", result.model.role);
          setValue("status", result.model.status);
          setOldEmail(result.model.email);
          setId(result.model.id);
        }
      } catch (error) {
        console.log("Error", error);
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, [activeId]);
  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">Edit User</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-[#4F46E5] px-3 py-2 text-white shadow-sm"
            onClick={async () => {
              await handleSubmit(onSubmit)();
              setSidebar(false);
            }}
            disabled={isEditing}
          >
            {isEditing ? "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="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="email"
          >
            Email
          </label>
          <input
            type="email"
            {...register("email")}
            className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.email?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">{errors.email?.message}</p>
        </div>
        <div className="mb-4">
          <label className="mb-2 block text-sm font-bold text-gray-700">
            Role
          </label>
          <select
            className="focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
            {...register("role")}
          >
            {selectRole.map((option) => (
              <option name="role" value={option} key={option}>
                {option}
              </option>
            ))}
          </select>
        </div>
        <div className="mb-4">
          <label className="mb-2 block text-sm font-bold text-gray-700">
            Status
          </label>
          <select
            className="focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
            {...register("status")}
          >
            {selectStatus.map((option) => (
              <option name="status" value={option.key} key={option.key}>
                {option.value}
              </option>
            ))}
          </select>
        </div>
        <div className="mb-4">
          <label
            className="mb-2 block text-sm font-bold text-gray-700"
            htmlFor="password"
          >
            Password
          </label>
          <input
            type="password"
            placeholder="******************"
            {...register("password")}
            className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${errors.password?.message ? "border-red-500" : ""
              }`}
          />
          <p className="text-xs italic text-red-500">
            {errors.password?.message}
          </p>
        </div>
        {/* <button
          type="submit"
          className="bg-[#4F46E5] hover:opacity-90 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
        >
          Submit
        </button> */}
      </form>
    </div>
  );
};

export default EditAdminUserPage;
