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'
import 'bootstrap/dist/css/bootstrap.min.css'
import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'

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 <Container fluid>
    <Row>
      <Col>
        <UserSelector user={user} selectUser={selectUser} removeUser={removeUser} users={state?.players.map(p => p.name) ?? []} locked={state !== undefined && state.stage !== 'starting'} />
      </Col>
    </Row>
    {state
      ? <>
        <Row>
          <Col><Game state={state} dispatch={dispatch} playerName={user} /></Col>
        </Row>
        <Row>
          <Col>
            <button onClick={loadSample}>Load sample</button>
            {' '}
            <button onClick={resetGame}>Reset</button>
          </Col>
        </Row>
      </>
      : <Row><Col>Loading…</Col></Row>
    }
  </Container>
}
