import { useState } from "react";
import { APIResponse, api } from "../API/API";
import { NewProjMember } from "../Types/goTypes";
import Logo from "../assets/Logo.svg";
import Button from "./Button";
import GetAllUsers from "./GetAllUsers";

/**
 * Tries to add a member to a project
 * @param {Object} props - A NewProjMember
 * @returns {boolean} True if added, false if not
 */
function MemberAdd(props: { memberToAdd: NewProjMember }): boolean {
  let added = false;

  api
    .addUserToProject(
      props.memberToAdd,
      localStorage.getItem("accessToken") ?? "",
    )
    .then((response: APIResponse<NewProjMember>) => {
      if (response.success) {
        added = true;
      } else {
        console.error(response.message);
      }
    })
    .catch((error) => {
      console.error("An error occurred during member add:", error);
    });
  return added;
}

/**
 * Provides UI for adding a project to the system.
 * @returns {JSX.Element} - Returns the component UI for adding a project
 */
function AddUserToProject(): JSX.Element {
  const [name, setName] = useState("");
  const [users, setUsers] = useState<string[]>([]);
  const [role, setRole] = useState("");
  GetAllUsers({ setUsersProp: setUsers });

  const handleClick = (): boolean => {
    const newMember: NewProjMember = {
      username: name,
      projectname: localStorage.getItem("projectName") ?? "",
      role: "user",
    };
    return MemberAdd({ memberToAdd: newMember });
  };

  return (
    <div className="flex flex-col h-fit w-screen items-center justify-center">
      <div className="border-4 border-black bg-white flex flex-col items-center justify-center rounded-3xl content-center pl-20 pr-20  h-[84vh] w-[50vh]">
        <form
          className="bg-white rounded px-8 pt-6 pb-8 mb-4 items-center justify-center flex flex-col w-fit h-fit"
          onSubmit={(e) => {
            e.preventDefault();
            MemberAdd({
              memberToAdd: {
                username: "",
                projectname: "",
                role: "project_manager",
              },
            });
          }}
        >
          <img
            src={Logo}
            className="logo w-[7vw] mb-10 mt-10"
            alt="TTIME Logo"
          />
          <h3 className="pb-4 mb-2 text-center font-bold text-[18px]">
            Add {name} to {localStorage.getItem("projectName") ?? ""} as {role}
          </h3>
          <p className="p-1">Role for user:</p>
          <div className="border-2 border-black p-2 rounded-xl text-center h-[10h] w-[16vh]">
            <ul className="text-center items-center font-medium space-y-2">
              <li
                className="h-[10h] w-[14vh] items-start p-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer"
                onClick={() => {
                  setRole("user");
                }}
              >
                {"User"}
              </li>
              <li
                className="h-[10h] w-[14vh] items-start p-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer"
                onClick={() => {
                  setRole("project_manager");
                }}
              >
                {"Project manager"}
              </li>
            </ul>
          </div>
          <p className="p-1">User to add:</p>
          <div className="border-2 border-black p-2 rounded-xl text-center overflow-scroll h-[26vh] w-[26vh]">
            <ul className="text-center font-medium space-y-2">
              <div></div>
              {users.map((user) => (
                <li
                  className="items-start p-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer"
                  key={user}
                  value={user}
                  onClick={() => {
                    setName(user);
                  }}
                >
                  <span>{user}</span>
                </li>
              ))}
            </ul>
          </div>
          <div className="flex items-center justify-between">
            <Button
              text="Add"
              onClick={(): void => {
                handleClick();
              }}
              type="submit"
            />
          </div>
        </form>
        <p className="text-center text-gray-500 text-xs"></p>
      </div>
    </div>
  );
}

export default AddUserToProject;
