import React, { Component } from 'react';
import { connect } from 'react-redux';
import shallowequal from 'shallowequal';
import { withTheme, Row, Col, Visibility } from '@turntwo/react-ui';
import Link from 'next/link';

import Page from '../components/Page';
import PageHeader from '../components/PageHeader';
import PageContent from '../components/PageContent';
import ArticlesList from '../components/ArticlesList';
import Button from '../components/Button';
import GroupedByDate from '../components/GroupedByDate';
import TournamentTeaser from '../components/TournamentTeaser';
import TeamTeaser from '../components/TeamTeaser';
import OrganizationTeaser from '../components/OrganizationTeaser';
import Heading from '../components/Heading';
import RaisedBox from '../components/RaisedBox';

import api from '../utils/api';
import withAuth from '../utils/withAuth';

import { initialFollowsState } from '../store/reducers';

const mapStateToProps = state => ({ follows: state.follows });

const getFollowIds = follows => {
  const keys = ['games', 'teams', 'orgs'];
  const output = {};

  keys.forEach(key => {
    output[`${key}Ids`] = Object.keys(follows[key]).map(
      k => follows[key][k].id,
    );
  });

  return output;
};

class Dashboard extends Component {
  state = {
    articles: { data: [] },
    tournaments: { data: [] },
    teams: { data: [] },
    orgs: { data: [] },
  };

  fetchData = async (props = this.props) => {
    const { gamesIds, teamsIds, orgsIds } = getFollowIds(props.follows);

    const teams = await api.fetchTeamsById(teamsIds);
    const orgs = await api.fetchOrgsById(orgsIds);
    const tournaments = await api.fetchTournamentsByGamesAndTeams(gamesIds);
    const articles = await api.fetchArticlesByGamesAndTeams(
      gamesIds,
      teamsIds,
      5,
    );

    const data = await Promise.all([tournaments, teams, orgs, articles]);

    this.setState({
      tournaments: data[0],
      teams: data[1],
      orgs: data[2],
      articles: data[3],
    });
  };

  componentDidMount() {
    if (!shallowequal(this.props.follows, initialFollowsState)) {
      this.fetchData();
    }
  }

  componentDidUpdate(prevProps) {
    if (!shallowequal(this.props.follows, prevProps.follows)) {
      this.fetchData();
    }
  }

  render() {
    const { games, follows, theme } = this.props;
    const { articles, tournaments, teams, orgs } = this.state;

    return (
      <Page name="dashboard" title="Dashboard">
        <PageHeader title={`Welcome ${user.displayName}`} flex flexCenter>
          <Link href="/settings">
            <a
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                marginLeft: 'auto',
                lineHeight: 1,
              }}
              className="dashboard-settings-link"
            >
              <span className="material-icons dashboard-settings-icon">
                settings
              </span>
              <Visibility visible={['m']}>Edit Settings</Visibility>
            </a>
          </Link>
        </PageHeader>
        <PageContent>
          <div className="dashboard-section">
            <Row style={{ marginBottom: 24 }}>
              <Col sizes={{ m: 6 }} style={{ marginBottom: 24 }}>
                <ArticlesList title="Recent News" articles={articles} />
              </Col>
              <Col sizes={{ m: 6 }}>
                <Heading border spaceBetween>
                  Upcoming Touranments
                  <Button href="/tournaments">
                    View All{' '}
                    <span className="material-icons">chevron_right</span>
                  </Button>
                </Heading>
                <GroupedByDate
                  dateField="field_tournament_date"
                  entities={tournaments}
                >
                  {({ entity, included }) => (
                    <TournamentTeaser
                      tournament={entity}
                      included={included}
                      key={entity.id}
                    />
                  )}
                </GroupedByDate>
              </Col>
            </Row>
          </div>

          <div className="dashboard-section">
            <Heading border spaceBetween>
              Your Games
              <Button href="/games">
                View All
                <span className="material-icons">chevron_right</span>
              </Button>
            </Heading>
            <Row>
              {Object.keys(follows.games).map(key => {
                const fg = follows.games[key];
                const game = games.data.find(g => g.id === fg.id);

                return (
                  <Col
                    sizes={{ sm: 6, l: 4 }}
                    key={game.id}
                    style={{ marginBottom: 24 }}
                  >
                    <RaisedBox>
                      <Link href={`/game/${game.attributes.field_game_slug}`}>
                        <a style={{ display: 'block', padding: 16 }}>
                          {game.attributes.name}
                        </a>
                      </Link>
                    </RaisedBox>
                  </Col>
                );
              })}
            </Row>
          </div>

          <div className="dashboard-section">
            <Heading border spaceBetween>
              Your Teams
              <Button href="/teams">
                View All
                <span className="material-icons">chevron_right</span>
              </Button>
            </Heading>
            <Row>
              {teams.data.map(team => (
                <Col
                  sizes={{ sm: 6, l: 4 }}
                  key={team.id}
                  style={{ marginBottom: 24 }}
                >
                  <TeamTeaser team={team} included={teams.included} />
                </Col>
              ))}
            </Row>
          </div>

          <div className="dashboard-section">
            <Heading border spaceBetween>
              Your Organizations
              <Button href="/organizations">
                View All
                <span className="material-icons">chevron_right</span>
              </Button>
            </Heading>
            <Row>
              {orgs.data.map(org => (
                <Col
                  sizes={{ sm: 6, l: 4 }}
                  key={org.id}
                  style={{ marginBottom: 24 }}
                >
                  <OrganizationTeaser org={org} included={orgs.included} />
                </Col>
              ))}
            </Row>
          </div>
        </PageContent>
        <style jsx>{`
          .dashboard-section {
            margin-bottom: ${theme.baseSpacingUnit}px;
          }

          @media (min-width: ${theme.breakpoints.m}px) {
            .dashboard-settings-icon {
              margin-right: 4px;
            }
          }
        `}</style>
      </Page>
    );
  }
}

export default withTheme(connect(mapStateToProps)(withAuth(Dashboard)));
