import React, { useEffect, useState } from "react";
import logo from "./kaistevenson.svg";
import "./App.css";

import { Grid } from "./Grid";
import { getWords } from "./serverHelper";

export type GameState = {
  words: { word: string; selected: boolean; used: boolean }[];
  groups: { title: string; words: string[] }[];
};

const initializeGameState = async (): Promise<GameState> => ({
  words: (await getWords()).map((word) => ({
    word,
    selected: false,
    used: false,
  })),
  groups: [],
});

const Game = () => {
  //state
  const [gameState, setGameState] = useState<GameState | undefined>(undefined);

  //initialize
  useEffect(() => {
    if (!gameState) {
      initializeGameState()
        .then((state) => setGameState(state))
        .catch(console.error);
    }
  });

  //handlers
  const selectWordHandler = (idx: number) => {
    const candidateState = { ...gameState! };
    if (candidateState.words.filter((word) => word.selected).length === 4) {
      if (!candidateState.words[idx].selected) {
        //if we've already selected 4 words and we would select another,
        //do nothing
        return;
      }
    }
    //FIXME don't mutate state
    candidateState.words[idx].selected = !candidateState.words[idx].selected;
    setGameState(candidateState);
  };
  const submitSelectionHandler = () => {
    const candidateState = { ...gameState! };

    const selectedWords = candidateState.words
      .filter(({ selected }) => selected)
      .map(({ word }) => word);

    if (selectedWords.length !== 4) {
      return;
    }

    candidateState.words = candidateState.words.map(
      ({ selected, word, used }) => ({
        used: used || selected,
        selected: false,
        word,
      })
    );

    //mock the server response for this selection
    const response = "Four letter verbs";
    const newGroup: GameState["groups"][number] = {
      title: response,
      words: selectedWords,
    };
    candidateState.groups = [...candidateState.groups, newGroup];

    setGameState(candidateState);
  };

  //display logic
  return gameState ? (
    <Grid
      selectWordHandler={selectWordHandler}
      submitSelectionHandler={submitSelectionHandler}
      gameState={gameState!}
    />
  ) : (
    <h1>Loading...</h1>
  );
};

export const App = () => (
  <div className="App">
    <div className="App-bg">
      <div className="Logo-container">
        <img src={logo} className="App-logo" alt="logo" />
      </div>
      <div className="App-main">
        <Game />
      </div>
    </div>
  </div>
);
