import ConfirmModal from "Components/Modal/ConfirmModal";
import React, { useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import {
  AssignClient,
  getAllMemberAssignedToClient,
  viewClientDetails,
} from "Src/services/clientService";
import { getAllMembersForManager } from "Src/services/managerServices";
import { deleteUserAPI } from "Src/services/userService";
import { AuthContext, tokenExpireError } from "../../authContext";
import { GlobalContext, showToast } from "../../globalContext";
import MkdSDK from "../../utils/MkdSDK";
import CustomSelect2 from "Components/CustomSelect2";

let sdk = new MkdSDK();

const ViewClientPageManager = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [viewModel, setViewModel] = React.useState({});
  const [deleteItemId, setDeleteItemId] = React.useState(null);
  const [showDeleteClientModal, setShowDeleteClientModal] =
    React.useState(false);
  const [clientData, setClientData] = useState({});
  const [AssignedMembers, setAssignedMembers] = React.useState([]);
  const [producersForSelect, setProducersForSelect] = React.useState([]);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");

  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();

  const handleDeleteClientModalClose = () => {
    setShowDeleteClientModal(false);
  };

  const getAllProducers = async () => {
    try {
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );

      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;

          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return { ...row };
          });

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

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

  const handleDeleteClient = async () => {
    try {
      let filteredArray = AssignedMembers.filter(
        (item) => item != selectedMemberId
      );

      if (filteredArray.length <= 0) {
        const res = await deleteUserAPI(params?.id, viewModel?.email);

        showToast(globalDispatch, "Client deleted successfully", 4000);
        setShowDeleteClientModal(false);
        navigate(`/${authState.role}/clients`);
      } else {
        const result = await assignClientToMember(
          {
            member_ids: filteredArray,
          },
          parseInt(params.id)
        );
        if (!result.error) {
          setShowDeleteClientModal(false);
          navigate(`/${authState.role}/clients`);
          showToast(
            globalDispatch,
            "Client Sucessfully Unassigned from Member",
            4000
          );
        } else {
          setShowDeleteClientModal(false);
          showToast(globalDispatch, result.message, 4000, "error");
        }
      }
    } catch (err) {
      showToast(globalDispatch, err.message, 4000, "error");
      setShowDeleteClientModal(false);
      tokenExpireError(dispatch, err.message);
    }
  };

  React.useEffect(function () {
    (async function () {
      try {
        sdk.setTable("client");
        const res = await getAllMemberAssignedToClient(params?.id);
        const result = await viewClientDetails(params?.id);

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

        if (!result.error) {
          setViewModel(result.model);
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  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">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <h3 className="text-xl font-medium text-white">View Client</h3>
              <div className="flex flex-wrap items-center gap-3">
                <button
                  onClick={() => navigate(-1)}
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-4 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Back
                </button>
                <button
                  onClick={() => {
                    navigate(`/${authState.role}/edit-client/` + params?.id, {
                      state: location?.state,
                    });
                  }}
                  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"
                >
                  Edit
                </button>
                <button
                  onClick={() => {
                    if (!selectedMemberId) {
                      showToast(
                        globalDispatch,
                        "Select a member to whom client will be removed from",
                        4000,
                        "error"
                      );
                    } else {
                      setShowDeleteClientModal(true);
                      setDeleteItemId(params?.id);
                    }
                  }}
                  className="inline-flex items-center justify-center rounded-md bg-danger px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>

          <div className="p-4 md:p-6 2xl:p-10">
            <div className="space-y-6">
              {/* Producer Selection */}
              <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                <span className="text-sm text-gray-400">Producers</span>
                <div className="mt-1">
                  <CustomSelect2
                    className="w-full max-w-[300px] rounded border border-strokedark bg-form-input px-3 py-2 text-white outline-none focus:border-primary"
                    value={selectedMemberId}
                    label="Select Producer"
                    onChange={(value) => {
                      setSelectedMemberId(value);
                    }}
                  >
                    <option value="">--Select--</option>
                    {clientData?.members &&
                      clientData?.members.length > 0 &&
                      clientData?.members.map((row, i) => (
                        <option key={i} value={row.id}>
                          {row.full_name}
                        </option>
                      ))}
                  </CustomSelect2>
                </div>
              </div>

              <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                <div className="space-y-4">
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Program</span>
                    <p className="mt-1 text-base font-medium text-white">
                      {viewModel?.program || "N/A"}
                    </p>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Position</span>
                    <p className="mt-1 text-base font-medium text-white">
                      {viewModel?.position || "N/A"}
                    </p>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Name</span>
                    <p className="mt-1 text-base font-medium text-white">
                      {viewModel?.name || "N/A"}
                    </p>
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Email</span>
                    <p className="mt-1 text-base font-medium text-white">
                      {viewModel?.email || "N/A"}
                    </p>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Phone</span>
                    <p className="mt-1 text-base font-medium text-white">
                      {viewModel?.phone || "N/A"}
                    </p>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">
                      Members Assigned
                    </span>
                    <p className="mt-1 text-base font-medium text-white">
                      {clientData?.members?.length > 0
                        ? clientData.members
                            .map((elem) => elem?.full_name)
                            .join(", ")
                        : "No members assigned"}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {showDeleteClientModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this client?`}
          setModalClose={handleDeleteClientModalClose}
          setFormYes={handleDeleteClient}
        />
      ) : null}
    </>
  );
};

export default ViewClientPageManager;
