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

let sdk = new MkdSDK();

const ViewClientPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [AssignedMembers, setAssignedMembers] = React.useState([]);

  const [viewModel, setViewModel] = React.useState({});
  const [deleteItemId, setDeleteItemId] = React.useState(null);
  const [showDeleteClientModal, setShowDeleteClientModal] =
    React.useState(false);
  const [clientData, setClientData] = useState({});

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

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

  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 != parseInt(localStorage.getItem("user"))
      );
      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 result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        const res = await getAllMemberAssignedToClient(params?.id);

        if (!res?.error) {
          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(viewModel);

  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: params?.id,
                    });
                  }}
                  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={() => {
                    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">
              <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}
        />
      )}
    </>
  );
};

export default ViewClientPage;
