import React, { useEffect, useState } from 'react';
import useKetchup from 'ketchup-react'
import { addPlayerAction, reducer, removePlayerAction, resetAction } from 'wonders-common'
import './App.css';
import Game from '../Game/Game';
import UserSelector from '../UserSelector/UserSelector';

export default function App() {
  const [state, dispatch] = useKetchup('ws://localhost:4000', reducer)
  useEffect(() => {
    console.debug('State', state)
  }, [state])

  const [user, setUser] = useState<string>()
  function selectUser(name?: string) {
    setUser(name)
    if (name && !state?.players.some(p => p.name === name)) {
      dispatch(addPlayerAction(name))
    }
  }
  function removeUser() {
    if (user !== undefined) {
      dispatch(removePlayerAction(user))
      setUser(undefined)
    }
  }

  return <>
    <UserSelector user={user} selectUser={selectUser} removeUser={removeUser} users={state?.players.map(p => p.name) ?? []} locked={state !== undefined && state.stage !== 'starting'}/>
    {state
      ? <>
        <Game state={state} dispatch={dispatch} playerName={user}/>
        <button onClick={() => window.confirm('Reset game?') && dispatch(resetAction())}> Reset</button>
      </>
      : <p>Loading...</p>
    }
  </>
}
