import { yupResolver } from "@hookform/resolvers/yup";
import Spinner from "Components/Spinner";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import {
  AssignClient,
  addClientAPI,
  getAllClientsAPI,
  getAllMemberAssignedToClient,
} from "Src/services/clientService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import {
  getUserDetailsByIdAPI,
  retrieveAllUserAPI,
} from "Src/services/userService";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import CustomSelect from "Components/CustomSelect";
import CustomSelect2 from "Components/CustomSelect2";

const AddClientPageAdmin = () => {
  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 [members, setMembers] = React.useState([]);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");
  const [subscriptionType, setSubscriptionType] = React.useState("");
  const [AssignedMembers, setAssignedMembers] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);

  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 getClients = async () => {
    const res = await getAllClientsAPI();
    if (!res.error) {
      const availClient = res.list.filter((user) => {
        return (
          (user?.members && user?.members.length === 0) ||
          !user?.members?.some((obj) => obj.id == selectedMemberId)
        );
      });

      console.log(availClient);

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

      setClients(list);
    }
  };

  const retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
      };
      const result = await retrieveAllUserAPI(1, 5000, filter);
      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;
          // concat first_name and last_name into user_name
          // then sort by ascending order of user_name
          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return row;
          });
          list = list.sort((a, b) => {
            return a.user_name.localeCompare(b.user_name);
          });

          setMembers(list);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const assignClientToMember = async (payload, id) => {
    const res = await AssignClient(payload, id);
    if (!res.error) {
    }
  };

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

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

  React.useEffect(() => {
    const userId = selectedMemberId;

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

          if (!result?.error) {
            setSubscriptionType(result?.model?.subscription);
          }
        } catch (error) {}
      })();
    }
  }, [selectedMemberId]);

  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 () {
        const res = await getAllMemberAssignedToClient(selectedclientId);

        if (!res?.error) {
          const memberIds = res.model.members.map((obj) => obj.id);
          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 (!selectedMemberId) {
        showToast(globalDispatch, "Please select a member");
      } else if (!selectedclientId && selectedMemberId) {
        const result = await addClientAPI({
          user_id: selectedMemberId,
          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);

            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;
        }
      } else if (selectedclientId && selectedMemberId) {
        const clientData =
          clients.find((elem) => elem.id == selectedclientId) || null;
        const UserData = members.find((elem) => elem.id == selectedMemberId);

        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- ${
            UserData.first_name + " " + UserData.last_name
          }</p><p>Company Name- ${
            UserData.company_name
          }</p>.</p> <p>If you have any questions please email ${
            UserData?.office_email || ""
          } . 
</p></br> <p>Thank you,

myEQ Admin</p> `,
        };
        const result2 = await sendEmailAPIV3(payload);

        await assignClientToMember(
          { member_ids: [...AssignedMembers, selectedMemberId] },
          parseInt(selectedclientId)
        );

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

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

  const clientData =
    clients.find((elem) => elem.client_id == selectedclientId) || null;
  console.log(selectedclientId, clientData);
  console.log(clients, "clients");

  const handleProducerChange = (value) => {
    setValue("program", "");
    setValue("position", "");
    setValue("last_name", "");
    setValue("first_name", "");
    setValue("email", "");
    setValue("phone", "");
    setSelectedclientId("");
    setSelectedMemberId(value);
  };

  if (isLoading) {
    return <Spinner />;
  }
  return (
    <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">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">
                Producers
              </label>
              <CustomSelect2
                className="h-11 !w-full"
                label="Select Producer"
                options={
                  members && members.length > 0
                    ? [
                        { value: "", label: "All Members" },
                        ...members.map((member) => ({
                          value: member.id,
                          label: member.user_name,
                        })),
                      ]
                    : []
                }
                value={selectedMemberId}
                onChange={handleProducerChange}
              />
            </div>

            <div>
              <label className="mb-2.5 block font-medium text-white">
                Available Clients
              </label>
              <CustomSelect2
                className="h-11 !w-full"
                label="Select Client"
                options={
                  selectedMemberId &&
                  clients.map((client) => ({
                    value: client.id,
                    label: client.client_program,
                  }))
                }
                value={selectedclientId}
                onChange={setSelectedclientId}
              />
            </div>

            <div>
              <label className="mb-2.5 block font-medium text-white">
                Program
              </label>
              <input
                placeholder="Program"
                {...register("program")}
                readOnly={selectedclientId && selectedMemberId}
                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 && selectedMemberId}
                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 && selectedMemberId}
                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 && selectedMemberId}
                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 && selectedMemberId}
                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 Number
              </label>
              <input
                placeholder="Phone"
                {...register("phone")}
                readOnly={selectedclientId && selectedMemberId}
                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>

            {selectedclientId && clientData?.members?.length > 0 && (
              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Currently assigned-to members
                </label>
                <textarea
                  placeholder="member"
                  value={clientData?.members
                    ?.map((elem) => elem?.full_name)
                    .join(", ")}
                  readOnly
                  className="w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 font-medium text-white outline-none"
                />
              </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"
            >
              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 AddClientPageAdmin;
