import { useState } from 'react'
import useKetchup from 'ketchup-react'
import { addPlayerAction, loadSampleAction, 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)

  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)
    }
  }

  function resetGame() {
    if (window.confirm('Reset game?')) {
      dispatch(resetAction())
      setUser(undefined)
    }
  }

  function loadSample() {
    if (window.confirm('Load sample game state?')) {
      dispatch(loadSampleAction())
    }
  }

  return <div className='wonder-outer'>
    <div className='wonder-top-bar'>
      <UserSelector user={user} selectUser={selectUser} removeUser={removeUser} users={state?.players.map(p => p.name) ?? []} disabled={state !== undefined && state.stage !== 'starting'} />
      <div>
        <button onClick={loadSample} disabled={!state}>Load sample</button>
        {' '}
        <button onClick={resetGame} disabled={!state}>Reset</button>
      </div>
    </div>
    <div className='wonder-game-wrapper'>
      {state
        ? <Game state={state} dispatch={dispatch} playerName={user} />
        : <div>Loading…</div>
      }
    </div>
  </div>
}
