import React from 'react';
import { connect } from 'react-redux';

import { appReducers } from './index';

import * as ActionsPokemonExplorer from './components/PokemonExplorer/actions';
import * as ActionsPokemonSelectList from './components/PokemonSelectList/actions';
import { ThunkDispatchPokemonSelectList } from './types';

import { PokemonExplorer } from './components/PokemonExplorer/PokemonExplorer';
import { PokemonSelectList } from './components/PokemonSelectList/PokemonSelectList';

type PokemonAppProps = ReturnType<typeof appReducers>;

interface IConnectedPokemonAppProps extends PokemonAppProps {
    dispatch : ThunkDispatchPokemonSelectList;
}

class PokemonApp extends React.Component<IConnectedPokemonAppProps> {
    constructor(props : IConnectedPokemonAppProps) {
        super(props);
    }

    public componentWillMount() {
        this.props.dispatch(ActionsPokemonSelectList.fetchPokemonList())
        .then(() => this.props.dispatch(ActionsPokemonSelectList.setIsLoading(false)));
    }

    public render() {
        const {
            activePokemonIndex,
            pokemonList,
        } = this.props.pokemonSelectListState;
        const {
            leaguePokemon,
        } = this.props.pokemonExplorerState;

        return (
            <div>
                <PokemonSelectList
                    isLoading={ this.props.pokemonSelectListState.isLoading }
                    activePokemonIndex={ activePokemonIndex }
                    pokemonList={ pokemonList }
                    onActivatePokemon={ this.onActivatePokemon }
                />
                { leaguePokemon !== null &&
                    <PokemonExplorer
                        isLoading={ this.props.pokemonExplorerState.isLoading }
                        leaguePokemon={ leaguePokemon }
                    />
                }
            </div>
        );
    }

    private readonly onActivatePokemon = (pokemonIndex : number) => {
        const { dispatch, pokemonSelectListState } = this.props;
        const pokemonId = pokemonSelectListState.pokemonList[pokemonIndex].id;

        dispatch(ActionsPokemonSelectList.fetchPokemonLeagueStats(pokemonId))
        .then((leaguePokemon) => {
            dispatch(ActionsPokemonSelectList.setActivePokemonIndex(pokemonIndex));
            dispatch(ActionsPokemonExplorer.setLeaguePokemon(leaguePokemon));
        })
        .catch((error) => {
            // tslint:disable-next-line:no-console
            console.error(error);
            dispatch(ActionsPokemonExplorer.setLeaguePokemon(null));
        })
        .then(() => dispatch(ActionsPokemonExplorer.setIsLoading(false)));
    }
}

const mapStateToProps = (state : ReturnType<typeof appReducers>) : PokemonAppProps => {
    return {
        pokemonExplorerState: state.pokemonExplorerState,
        pokemonSelectListState: state.pokemonSelectListState,
    };
};

export const ConnectedPokemonApp = connect(mapStateToProps)(PokemonApp);
