import React from "react";
import { AuthContext } from "@/context/Auth";
import { GlobalContext } from "@/context/Global";
import MkdSDK from "@/utils/MkdSDK";

const columns = [
  {
    header: "user_id",
    accessor: "user_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "first name",
    accessor: "first_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "last name",
    accessor: "last_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Action",
    accessor: "",
  },
];

export const PmWorkspaceMembers = ({ activeWorkspaceId }) => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [addMemberForm, setAddMemberForm] = React.useState(false);
  const [users, setUsers] = React.useState([]);

  async function getUsers() {
    let sdk = new MkdSDK();
    try {
      const result = await sdk.getAllUsers();
      setUsers(result.list.filter((item) => item.role == "user"));
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const assigneMember = async (id) => {
    let sdk = new MkdSDK();
    try {
      const result = await sdk.callRawAPI(
        `/v2/api/lambda/pm/workspaces/${activeWorkspaceId}/members/${id}/attach`,
        {},
        "POST"
      );
      if (!result.error) {
        showToast(globalDispatch, "User Added");
        getWorkspaceMember();
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };
  const getWorkspaceMember = async () => {
    let sdk = new MkdSDK();
    try {
      const result = await sdk.callRawAPI(
        `/v2/api/lambda/pm/workspaces/${activeWorkspaceId}/members`,
        {},
        "GET"
      );
      if (!result.error) {
        setCurrentTableData(result.list);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "workspaceMembers",
      },
    });
    (async function () {
      await getUsers();
    })();
    (async function () {
      await getWorkspaceMember();
    })();
  }, []);

  return (
    <>
      <div className="w-full   overflow-y-auto ">
        <div className="mx-[auto] shadow-lg ">
          <div className=" flex w-full justify-between px-5 py-1 text-center ">
            <h4 className="text-2xl font-medium">Member</h4>
            <div className="flex">
              <button
                onClick={() => setAddMemberForm(true)}
                className=" rounded-[4px] px-1 py-1 hover:bg-[#d6eaff]  hover:shadow-[0_0_3px_1px_#1111115e] "
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth="1.5"
                  stroke="currentColor"
                  className="h-6 w-6"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M12 4.5v15m7.5-7.5h-15"
                  />
                </svg>
              </button>
            </div>
          </div>
          <div className="mt-4 overflow-x-auto border-b border-gray-200  shadow">
            <table className="min-w-full divide-y divide-gray-200  ">
              <thead className="bg-gray-50">
                <tr>
                  {columns.map((column, i) => (
                    <th
                      key={i}
                      scope="col"
                      className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
                      onClick={() => onSort(i)}
                    >
                      {column.header}
                      <span>
                        {column.isSorted
                          ? column.isSortedDesc
                            ? " ▼"
                            : " ▲"
                          : ""}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white">
                {currentTableData.map((row, i) => {
                  return (
                    <tr key={i}>
                      {columns.map((cell, index) => {
                        if (cell.accessor == "parent_id") {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              {row[cell.accessor] > 0
                                ? categories.filter(
                                    (cat) => cat.id == row[cell.accessor]
                                  )[0]?.name
                                : ""}
                            </td>
                          );
                        }
                        if (cell.accessor.indexOf("image") > -1) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              <img
                                src={row[cell.accessor]}
                                className="h-[100px] w-[150px]"
                              />
                            </td>
                          );
                        }
                        if (cell.accessor == "") {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              <button
                                className="text-xs"
                                onClick={() => {
                                  navigate(
                                    "/admin/edit-ecom_category/" + row.id,
                                    {
                                      state: row,
                                    }
                                  );
                                }}
                              >
                                {" "}
                                Edit
                              </button>
                              <button
                                className="px-1 text-xs text-blue-500"
                                onClick={() => {
                                  navigate(
                                    "/admin/view-ecom_category/" + row.id,
                                    {
                                      state: row,
                                    }
                                  );
                                }}
                              >
                                {" "}
                                View
                              </button>
                              <button
                                className="px-1 text-xs text-red-500"
                                onClick={() => deleteItem(row.id)}
                              >
                                {" "}
                                Delete
                              </button>
                            </td>
                          );
                        }
                        if (cell.mappingExist) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              {cell.mappings[row[cell.accessor]]}
                            </td>
                          );
                        }
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor] ? row[cell.accessor] : "N/A"}
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
      {addMemberForm && (
        <div className=" fixed  left-0 top-0 z-[9999] h-full w-full">
          <div
            onClick={() => setAddMemberForm(false)}
            className=" absolute left-0 top-0 h-full w-full bg-[#0000004f] "
          />
          <div className="min-h-1/2 max-h-1/2 absolute  left-1/2 top-1/2 w-1/4 -translate-x-1/2 -translate-y-1/2 bg-white ">
            <h5 className=" relative border-b border-[#5e6c84] py-2 text-center text-[#5e6c84] ">
              Add Member
              <button
                className=" absolute  right-0 top-0  flex  h-[35px] w-[35px] items-center justify-center rounded-3xl border-none text-lg text-[#031d2c] hover:bg-[#dcdcdc]"
                onClick={() => setAddMemberForm(false)}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth="1.5"
                  stroke="currentColor"
                  className="h-6 w-6"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </h5>

            <div className="px-5 py-5">
              <div className=" w-full max-w-lg">
                <div className="mb-4 ">
                  {users.map((item, i) => (
                    <div
                      key={i}
                      className="mb-3 flex cursor-pointer items-center rounded-md bg-[#eaf6ff] px-3 py-1 hover:bg-[#d3e3ff]  "
                      onClick={() => assigneMember(item.id)}
                    >
                      <p className=" mr-3 flex h-[40px] w-[40px] items-center justify-center rounded-full bg-[#DE350B] text-[16px] font-bold uppercase text-white ">
                        {item.first_name
                          ? item.first_name.substring(0, 1)
                          : "N"}
                        {item.last_name ? item.last_name.substring(0, 1) : "/A"}
                      </p>
                      <h4 className="text-lg">
                        {" "}
                        {`${
                          item.first_name
                            ? `${item.first_name} ${
                                item.last_name ? item.last_name : "N/A"
                              }`
                            : "N/A"
                        }`}
                      </h4>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};
