import { useState } from 'react';

function CodeDisplay({ code, isConnected, onCreateRoom, onJoinRoom, joinCode, setJoinCode }) {
  //const [showCode, setShowCode] = useState(true);

  const handleJoin = () => {
    if (joinCode) {
      //const trimCode=(joinCode.charAt(joinCode.length-1)==" ")?joinCode.substr(0,joinCode.length-1):joinCode;
      const trimCode = joinCode.trim();
      onJoinRoom(trimCode);
    }
  };

  const handleKeyJoin = (e) => {
    if (e.key === 'Enter') {
      handleJoin();
    }
  };

  return (
    <div className="mb-2">
      {!code ? (
        <>
          <button
            onClick={onCreateRoom}
            className="bg-purple-600 text-darkPurple px-4 py-2 rounded hover:bg-purple-500"
          >
          Create Room
          </button>
          <div className="inline-block whitespace-nowrap">
            <input
              type="text"
              className="width-212"
              value={joinCode}
              onChange={(e) => setJoinCode(e.target.value)}
              onKeyDown={handleKeyJoin}
              placeholder="Enter code to join"
            />
            <button
              onClick={handleJoin}
              className="bg-purple-600 text-darkPurple px-4 py-2 rounded hover:bg-purple-500"
            >
            Join
            </button>
          </div>
        </>
      ) : (
        <>
          {/*{isConnected ? (
            <button onClick={() => setShowCode(true)}>Show Code</button>
          ) : (*/}
            <p className="text-lg">Code: <strong className="text-3xl">{code}</strong></p>
          {/*)}*/}
        </>
      )}
    </div>
  );
}

export default CodeDisplay;
