import ConfirmModal from "Components/Modal/ConfirmModal";
import React, { useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import {
  AssignClient,
  getAllMemberAssignedToClient,
} from "Src/services/clientService";
import { deleteUserAPI, retrieveAllUserAPI } 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 ViewClientPageAdmin = () => {
  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 [members, setMembers] = React.useState([]);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");

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

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

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

  const handleDeleteClient = async () => {
    try {
      console.log(selectedMemberId);
      let filteredArray = AssignedMembers.filter(
        (item) => item != selectedMemberId
      );
      console.log(filteredArray);
      if (filteredArray.length <= 0 || !selectedMemberId) {
        console.log(deleteItemId, viewModel?.email);
        const res = await deleteUserAPI(deleteItemId, viewModel?.email);

        showToast(globalDispatch, "Client deleted successfully", 4000);
        setShowDeleteClientModal(false);
        navigate(`/${authState.role}/clients`);
      } else {
        const result = await assignClientToMember(
          {
            member_ids: filteredArray,
          },
          parseInt(clientData.client_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);
    }
  };

  const retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
      };
      const result = await retrieveAllUserAPI(1, 10000, 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);
    }
  };

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

        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);
      }
    })();
  }, []);

  console.log(clientData, viewModel);

  return (
    <>
      <div className="mx-auto rounded p-5 text-white shadow-md">
        <div className="flex flex-row justify-between">
          <div className="flex w-1/2 flex-row">
            <h4 className="text-2xl font-medium">View Client</h4>
          </div>
          <div className="flex w-1/2 flex-row gap-2">
            <button
              className="rounded bg-gray-500 px-2 py-1 text-xs font-semibold text-white hover:bg-gray-600 md:text-sm"
              onClick={() => navigate(-1)}
            >
              Back
            </button>
            <button
              className="rounded bg-blue-500 px-2 py-1 text-xs font-semibold text-white hover:bg-blue-600 md:text-sm"
              onClick={() => {
                navigate(`/${authState.role}/edit-client/` + params?.id, {
                  state: location?.state,
                });
              }}
            >
              Edit
            </button>
            <button
              className="rounded bg-red-500 px-2 py-1 text-xs font-semibold text-white hover:bg-red-600 md:text-sm"
              onClick={() => {
                setShowDeleteClientModal(true);
                setDeleteItemId(clientData?.client_user_id);
              }}
            >
              Delete
            </button>
          </div>
        </div>

        <div className="my-4">
          {" "}
          <div className="mb-4 flex">
            <div className="flex-1">Producers</div>
            <div className="flex-1">
              <CustomSelect2
                className={`focus:shadow-outline w-[300px] max-w-[300px] appearance-none items-start rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none`}
                value={selectedMemberId}
                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>

        <div className="my-4">
          <div className="mb-4 flex">
            <div className="flex-1">Program</div>
            <div className="flex-1">{viewModel?.program}</div>
          </div>
        </div>

        <div className="my-4">
          <div className="mb-4 flex">
            <div className="flex-1">Position</div>
            <div className="flex-1">{viewModel?.position}</div>
          </div>
        </div>

        <div className="my-4">
          <div className="mb-4 flex">
            <div className="flex-1">Name</div>
            <div className="flex-1">{viewModel?.name}</div>
          </div>
        </div>

        <div className="my-4">
          <div className="mb-4 flex">
            <div className="flex-1">Email</div>
            <div className="flex-1">{viewModel?.email}</div>
          </div>
        </div>

        <div className="my-4">
          <div className="mb-4 flex">
            <div className="flex-1">Phone</div>
            <div className="flex-1">{viewModel?.phone}</div>
          </div>
        </div>
        <div className="my-4">
          <div className="mb-4 flex">
            <div className="flex-1">Members assigned-to</div>
            <div className="flex-1">
              {clientData?.members?.map((elem) => elem?.full_name).join(", ")}
            </div>
          </div>
        </div>
      </div>
      {showDeleteClientModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this client?`}
          setModalClose={handleDeleteClientModalClose}
          setFormYes={handleDeleteClient}
        />
      ) : null}
    </>
  );
};

export default ViewClientPageAdmin;
