import { yupResolver } from "@hookform/resolvers/yup";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import {
  AssignClient,
  addClientAPI,
  getAllClientsAPI,
  getAllMemberAssignedToClient,
} 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 CustomSelect2 from "Components/CustomSelect2";

const AddClientPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [enableLogin, setEnableLogin] = React.useState("yes");
  const [selectedclientId, setSelectedclientId] = React.useState(null);
  const [clients, setClients] = React.useState([]);
  const [AssignedMembers, setAssignedMembers] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [officeEmail, setOfficeEmail] = useState("");

  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 {
    register,
    handleSubmit,
    setError,
    setValue,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

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

  const getClients = async () => {
    const res = await getAllClientsAPI();
    if (!res.error) {
      const availClient = res.list.filter((user) => {
        return (
          !user.members ||
          !user?.members?.some((obj) => obj.id == localStorage.getItem("user"))
        );
      });

      let list = availClient.sort((a, b) => {
        if (a.client_program?.toLowerCase() < b.client_program?.toLowerCase()) {
          return -1;
        }
        return 1;
      });
      //

      setClients(list);
    }
  };

  const assignClientToMember = async (payload, id) => {
    try {
      const res = await AssignClient(payload, id);
      return res;
    } catch (error) {}
  };

  React.useEffect(() => {
    getClients();
  }, []);

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

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

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

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

  function splitFullName(fullName) {
    // Split the full name into an array of parts
    const nameParts = fullName.split(" ");

    // Extract the first name and last name
    let firstName = nameParts[0];
    let lastName = nameParts.slice(1).join(" ");

    // Return an object containing the first name and last name
    return {
      firstName: firstName,
      lastName: lastName,
    };
  }

  React.useEffect(() => {
    if (selectedclientId) {
      (async function () {
        setIsLoading(true);
        const res = await getAllMemberAssignedToClient(selectedclientId);

        if (!res?.error) {
          const memberIds = res.model.members.map((obj) => obj.id);
          console.log(memberIds);
          setAssignedMembers(memberIds);
        }

        setIsLoading(false);
      })();
      const clientData =
        clients.find((elem) => elem.client_id == selectedclientId) || null;

      if (clientData) {
        const name = splitFullName(clientData.client_full_name);

        setValue("program", clientData.client_program);
        setValue("position", clientData.client_position);
        setValue("last_name", name.lastName || " ");
        setValue("first_name", name.firstName);
        setValue("email", clientData.client_email);
        setValue("phone", clientData.client_phone);
        setEnableLogin(clientData.client_has_auth == 1 ? "yes" : "no");
      }
    } else {
      setValue("program", "");
      setValue("position", "");
      setValue("last_name", "");
      setValue("first_name", "");
      setValue("email", "");
      setValue("phone", "");
      setEnableLogin("no");
    }
  }, [selectedclientId]);

  const onSubmit = async (_data) => {
    try {
      if (selectedclientId) {
        const clientData =
          clients.find((elem) => elem.client_id == selectedclientId) || null;
        await assignClientToMember(
          {
            member_ids: [
              ...AssignedMembers,
              parseInt(localStorage.getItem("user")),
            ],
          },
          selectedclientId
        );

        console.log(clientData);

        let payload = {
          from: "myeq@equalityrecords.com",
          to: clientData.client_email,
          subject: `MyEQ. Assigned to a new Producer.
                  `,
          body: `<p>Hello <b>${
            clientData?.client_program
          }</b>,</p> <p>We are excited to let you know that you have been added to the following producers calendar:<p>Producer Name- ${localStorage.getItem(
            "userName"
          )}</p><p>Company Name- ${localStorage.getItem("companyName")}</p>.</p>
          <p>If you have any questions please email ${officeEmail || ""} . 
</p></br> <p>Thank you,
W
myEQ Admin</p> `,
        };
        const result2 = await sendEmailAPIV3(payload);

        navigate(`/${authState.role}/clients`);
        showToast(globalDispatch, "Client added Successfully");
      } else {
        const result = await addClientAPI({
          user_id: parseInt(localStorage.getItem("user")),
          program: _data.program,
          position: _data.position,
          first_name: _data.first_name,
          last_name: _data.last_name,
          email: _data.email,
          phone: _data.phone,
          has_auth: SubscriptionType > 1 && 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);

            if (!result2.error) {
              reset();

              showToast(globalDispatch, result.message, 5000);
              showToast(globalDispatch, "Client added Successfully");

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

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

  const clientData =
    clients.find((elem) => elem.client_id == selectedclientId) || null;
  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <ClipLoader color="#fff" size={30} />
      </div>
    );
  }

  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">
        <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">Add 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">
                Available Clients
              </label>
              <CustomSelect2
                label="Available Clients"
                className={`w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5  py-3 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`}
                value={selectedclientId}
                onChange={(value) => {
                  setSelectedclientId(value);
                }}
              >
                <option value="">--Select--</option>
                {clients &&
                  clients.length > 0 &&
                  clients.map((row, i) => (
                    <option key={i} value={row.client_id}>
                      {row.client_program}
                    </option>
                  ))}
              </CustomSelect2>
            </div>

            <div>
              <label className="mb-2.5 block font-medium text-white">
                Program
              </label>
              <input
                placeholder="Program"
                {...register("program")}
                readOnly={selectedclientId ? true : false}
                className={` w-full rounded border-[1.5px] border-form-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")}
                readOnly={selectedclientId ? true : false}
                className={` w-full rounded border-[1.5px] border-form-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")}
                readOnly={selectedclientId ? true : false}
                className={` w-full rounded border-[1.5px] border-form-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")}
                readOnly={selectedclientId ? true : false}
                className={` w-full rounded border-[1.5px] border-form-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
                placeholder="Email"
                {...register("email")}
                readOnly={selectedclientId ? true : false}
                className={` w-full rounded border-[1.5px] border-form-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")}
                readOnly={selectedclientId ? true : false}
                className={` w-full rounded border-[1.5px] border-form-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>

            {SubscriptionType > 1 && (
              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Enable Login
                </label>
                <CustomSelect2
                  value={enableLogin}
                  onChange={(value) => setEnableLogin(value)}
                  className={`w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5  py-3 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`}
                >
                  <option value="yes">Yes</option>
                  <option value="no">No</option>
                </CustomSelect2>
              </div>
            )}
          </div>

          <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>
  );
};

export default AddClientPage;
