import Button from "./Button";
import DeleteUser from "./DeleteUser";
import UserProjectListAdmin from "./UserProjectListAdmin";
import { useState } from "react";
import InputField from "./InputField";
import ChangeUsername from "./ChangeUsername";
import { StrNameChange } from "../Types/goTypes";

function UserInfoModal(props: {
  isVisible: boolean;
  username: string;
  onClose: () => void;
}): JSX.Element {
  const [showInput, setShowInput] = useState(false);
  const [newUsername, setNewUsername] = useState("");
  if (!props.isVisible) {
    return <></>;
  }

  const handleChangeNameView = (): void => {
    if (showInput) {
      setShowInput(false);
    } else {
      setShowInput(true);
    }
  };

  const handleClickChangeName = (): void => {
    const nameChange: StrNameChange = {
      prevName: props.username,
      newName: newUsername.replace(/ /g, ""),
    };
    ChangeUsername({ nameChange: nameChange });
  };

  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm 
      flex justify-center items-center"
    >
      <div className="border-4 border-black bg-white rounded-lg text-center flex flex-col">
        <div className="mx-10">
          <p className="font-bold text-[30px]">{props.username}</p>
          <p
            className="mb-[10px] hover:font-bold hover:cursor-pointer underline"
            onClick={handleChangeNameView}
          >
            (Change Username)
          </p>
          {showInput && (
            <div>
              <InputField
                label={"New username"}
                type={"text"}
                value={newUsername}
                onChange={function (e): void {
                  e.defaultPrevented;
                  setNewUsername(e.target.value);
                }}
              />
              <Button
                text={"Change"}
                onClick={function (): void {
                  handleClickChangeName();
                }}
                type={"submit"}
              />
            </div>
          )}
          <h2 className="font-bold text-[20px]">Member of these projects:</h2>
          <UserProjectListAdmin username={props.username} />
          <div className="items-center space-x-6">
            <Button
              text={"Delete"}
              onClick={function (): void {
                if (
                  window.confirm("Are you sure you want to delete this user?")
                ) {
                  DeleteUser({
                    usernameToDelete: props.username,
                  });
                }
              }}
              type="button"
            />
            <Button
              text={"Close"}
              onClick={function (): void {
                setNewUsername("");
                setShowInput(false);
                props.onClose();
              }}
              type="button"
            />
          </div>
        </div>
      </div>
    </div>
  );
}

export default UserInfoModal;
