import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import "./PlayerName.css";

type PlayerNameProps = {
  name?: string;
  setName: (s: string) => void;
};

const PlayerName: React.FC<PlayerNameProps> = ({ name, setName }) => {
  const [edit, setEdit] = useState<string | undefined>(name);

  const sendName = () => {
    setName(edit ?? "");
  };

  const nameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEdit(event.target.value);
  };

  const nameKeyPress = (event: React.KeyboardEvent) => {
    if ((event as React.KeyboardEvent<HTMLInputElement>).key === "Enter") {
      setName(edit ? edit : name ?? "");
    }
  };

  return (
    <div className="PlayerName">
      <TextField
        className="nameInput"
        onChange={nameChange}
        onKeyPress={nameKeyPress}
        label="Enter your name"
        variant="outlined"
        value={edit}
      />
      <Button onClick={sendName}>Set</Button>
    </div>
  );
};

export { PlayerName };
