import { yupResolver } from "@hookform/resolvers/yup";
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { updateClientAPI } from "Src/services/clientService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import MkdSDK from "../utils/MkdSDK";

let sdk = new MkdSDK();

const EditClientPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [enableLogin, setEnableLogin] = React.useState("yes");

  const schema = yup.object().shape({
    program: yup.string().required("Program is required"),
    position: yup.string().required("Position is required"),
    first_name: yup.string().required("First Name is required"),
    last_name: yup.string().required("Last Name is required"),

    email: yup.string().email().required("Email is required"),
    phone: yup.string().required("Phone is required"),
  });

  const navigate = useNavigate();

  const [isLoading, setIsLoading] = React.useState(false);
  const [id, setId] = useState(0);

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

  const params = useParams();

  function getFirstNameAndLastName(fullName) {
    const trimmedFullName = fullName.trim(); // Remove leading and trailing spaces
    const firstSpaceIndex = trimmedFullName.indexOf(" "); // Find the index of the first space

    if (firstSpaceIndex === -1 || firstSpaceIndex === 0) {
      return {
        firstName: trimmedFullName,
        lastName: "", // Empty string for last name
      };
    }

    const firstName = trimmedFullName.substring(0, firstSpaceIndex);
    const lastName = trimmedFullName.substring(firstSpaceIndex + 1);

    return {
      firstName,
      lastName,
    };
  }

  useEffect(function () {
    (async function () {
      try {
        setIsLoading(true);
        sdk.setTable("client");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");

        if (!result.error) {
          const { firstName, lastName } = getFirstNameAndLastName(
            result.model.name
          );

          setValue("program", result.model.program);
          setValue("position", result.model.position);
          setValue("first_name", firstName);
          setValue("last_name", lastName);
          setValue("email", result.model.email);
          setValue("phone", result.model.phone);
          setEnableLogin(result.model.has_auth === 1 ? "yes" : "no");

          setId(result.model.id);
          setIsLoading(false);
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  const SubscriptionType = localStorage.getItem("UserSubscription");

  React.useEffect(() => {
    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            localStorage.setItem("photo", result?.model?.photo);
            localStorage.setItem(
              "UserSubscription",
              result?.model?.subscription
            );
          }
        } catch (error) {}
      })();
    }
  }, []);

  const userCompanyName = localStorage.getItem("companyName");

  const onSubmit = async (_data) => {
    try {
      setIsLoading(true);
      const result = await updateClientAPI({
        id: id,
        program: _data.program,
        position: _data.position,
        first_name: _data.first_name,
        last_name: _data.last_name,
        email: _data.email,
        phone: _data.phone,
        has_auth: enableLogin === "yes" ? 1 : 0,
      });

      if (!result.error) {
        if (result?.password) {
          let payload = {
            from: "myeq@equalityrecords.com",
            to: _data.email,
            subject: ` Welcome to myEQ.
                  `,
            body: `
            <p>Hello <b>${_data.first_name} ${_data.last_name}</b>,</p>
             <p>You're now ready to access your portal and explore our services. Here are your login credentials:</p> 
             <p>URL: https://equalityrecords.com/client/login</p>
              <p>Email: ${_data.email}</p> 
              <p>Temporary Password: ${result.password}</p> 
              <p>Please note that this is a randomly generated password for your initial login. We strongly recommend updating your password for enhanced security once you log in by visiting the 'Edit Profile' section.</p> 
              <p>Thanks,</p>
              <p>${userCompanyName}</p>`,
          };
          const result2 = await sendEmailAPIV3(payload);
          setIsLoading(false);

          if (!result2.error) {
            reset();
            showToast(globalDispatch, result.message, 5000);
            showToast(globalDispatch, "Client Updated Successfully");

            navigate(`/${authState.role}/clients`);
            return;
          } else {
            showToast(globalDispatch, result.message, 5000, "error");
            return;
          }
        }
        navigate(`/${authState.role}/clients`);
        showToast(globalDispatch, "Client Updated Successfully");
        setIsLoading(false);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      setIsLoading(false);

      showToast(globalDispatch, error.message, 5000, "error");
    }
  };
  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "clients",
      },
    });
  }, []);

  return (
    <>
      {isLoading ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <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">
            <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 Client</h3>
            </div>

            <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">
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Program
                  </label>
                  <input
                    placeholder="Program"
                    {...register("program")}
                    className={`w-full rounded border-[2px] 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.program?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.program?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.program.message}
                    </p>
                  )}
                </div>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Position
                  </label>
                  <input
                    placeholder="Position"
                    {...register("position")}
                    className={`w-full rounded border-[2px] 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.position?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.position?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.position.message}
                    </p>
                  )}
                </div>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    First Name
                  </label>
                  <input
                    placeholder="First Name"
                    {...register("first_name")}
                    className={`w-full rounded border-[2px] 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.first_name?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.first_name?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.first_name.message}
                    </p>
                  )}
                </div>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Last Name
                  </label>
                  <input
                    placeholder="Last Name"
                    {...register("last_name")}
                    className={`w-full rounded border-[2px] 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.last_name?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.last_name?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.last_name.message}
                    </p>
                  )}
                </div>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Email
                  </label>
                  <input
                    readOnly
                    placeholder="Email"
                    {...register("email")}
                    className={`w-full rounded border-[2px] 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.email?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.email?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.email.message}
                    </p>
                  )}
                </div>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Phone
                  </label>
                  <input
                    placeholder="Phone"
                    {...register("phone")}
                    className={`w-full rounded border-[2px] 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.phone?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.phone?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.phone.message}
                    </p>
                  )}
                </div>

                {parseInt(SubscriptionType) > 1 && (
                  <div className="md:col-span-2">
                    <label className="mb-2.5 block font-medium text-white">
                      Are you sure you want to send credentials to client?
                    </label>
                    <div className="flex items-center gap-4">
                      <div className="flex items-center">
                        <input
                          type="radio"
                          value="yes"
                          checked={enableLogin === "yes"}
                          name="credential"
                          id="radio1"
                          className="mr-2 cursor-pointer"
                          onClick={(e) => setEnableLogin(e.target.value)}
                        />
                        <label
                          htmlFor="radio1"
                          className="cursor-pointer text-white"
                        >
                          Yes
                        </label>
                      </div>

                      <div className="flex items-center">
                        <input
                          type="radio"
                          value="no"
                          checked={enableLogin === "no"}
                          name="credential"
                          id="radio2"
                          className="mr-2 cursor-pointer"
                          onClick={(e) => setEnableLogin(e.target.value)}
                        />
                        <label
                          htmlFor="radio2"
                          className="cursor-pointer text-white"
                        >
                          No
                        </label>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <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 EditClientPage;
