
import "./RoomWidget.css";
import { useHotel } from "../context/HotelContext";
import { useState } from "react";



export default function RoomWidget({}) {

  const { rooms } = useHotel();

  return (
    <div className="roomGrid">
      {rooms.map(room => (
        <RoomCard
          key={room.id}
          id = {room.id}
          number={room.number}
          status={room.status}
        />
      ))}
    </div>
  );
}

function RoomCard({ number, status ,id}) {
  //FIXME: this shouldn't use hotel context, instead : set the state once on load
  const { updateRoomStatus } = useHotel();
  const [editing, setEdtiting] = useState(false);
  const [value, SetValue] = useState(status);

  function submit() {
    updateRoomStatus(id,value);
    setEdtiting(false);
  }

  function closeInput(){
    setEdtiting(false);    
  }

  return (
      <div className="card">
        <h3>Room {number}</h3>
        

        {!editing ?(
          <p onClick={() => setEdtiting(true)} style={{ cursor: "pointer" }}>
            Status: {status}
          </p>
        ): (
          <div>
            <input
            type="text"
            value={value}
            autoFocus
            onChange={e => SetValue(e.target.value)}
            onKeyDown={e => e.key === "Enter" && submit()}
            onBlur={closeInput}
            />
          </div>
        )}


        <div className="actions">
          <button onClick={() => updateRoomStatus(id, "clean")}>
            Mark Clean
          </button>

          <button onClick={() => updateRoomStatus(id, "dirty")}>
            Mark Dirty
          </button>
        </div>

      </div>
  );
}

//export default roomWidget