import { GlobalContext } from "@/context/Global";
import MkdSDK from "@/utils/MkdSDK";
import React from "react";
import { AddBoardsModal } from "./AddBoardsModal";

export const PmWorkspaceBoards = ({
  activeWorkspaceId,
  handleWorkspaceBoardClick,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [boards, setBoards] = React.useState([]);
  const [addWorkspaceOpen, setAddWorkspaceOpen] = React.useState(false);
  const sdk = new MkdSDK();

  const getBoards = async () => {
    try {
      const res = await sdk.getUserBoards(activeWorkspaceId);
      if (res) {
        setBoards(res.list);
      }
    } catch (err) {
      console.log("error" + " " + err);
    }
  };

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

  const onCloseAddWorkspaceModal = React.useCallback(() => {
    setAddWorkspaceOpen(false);
  }, [addWorkspaceOpen]);
  return (
    <>
      <div className=" h-full px-7">
        <div className=" flex w-full justify-between py-1 text-center ">
          <h1 className="mb-2 text-[1.3rem]">Boards</h1>
          <div className="flex">
            <button
              onClick={() => setAddWorkspaceOpen(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=" grid grid-cols-3 gap-2  ">
          {boards.length > 0
            ? boards?.map((board, _index) => (
                <div
                  key={_index}
                  onClick={() => handleWorkspaceBoardClick(board.id)}
                  className=" flex h-[100px] cursor-pointer items-center justify-center rounded bg-[#007A52] text-lg font-semibold text-white"
                  title={board.description}
                >
                  {board.name}
                </div>
              ))
            : null}
        </div>
      </div>

      <AddBoardsModal
        modalCloseClick={onCloseAddWorkspaceModal}
        modalHeader
        isOpen={addWorkspaceOpen}
        setAddWorkspaceOpen={setAddWorkspaceOpen}
        getData={getBoards}
        workspaceId={activeWorkspaceId}
      />
    </>
  );
};
