import React, { Component } from 'react';

const _ = require('lodash')

//import { makeStyles } from '@material-ui/core/styles';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import InputLabel from '@material-ui/core/InputLabel';

import { Chart } from "react-google-charts";

const teamData = require('../config/team-data.json');

export class ChartPanel extends Component {
  constructor(props) {
    super();
    this.state = {
      stats: null,
      splits: null,
      selects: {
        stats: [
          //{label: 'game-by-game', title: 'Season, By Game'},
          {label: 'yoy-totals', title: 'YoY Totals'},
          //{label: 'by-opp-team', title: 'Per Game, By Team'}
        ],
        splits: [
          {label: 'game-by-game', title: 'Season, By Game'},
          {label: 'by-opp-team', title: 'Per Game, By Team'}
        ]
      },
      selectType: 'stats',
      select1: '',
      select2: '',
      select3: '',
      data: null
    };
    
    this.changeSelectType = this.changeSelectType.bind(this);
    this.changeSelect1 = this.changeSelect1.bind(this);
    this.changeSelect2 = this.changeSelect2.bind(this);
    this.changeSelect3 = this.changeSelect3.bind(this);
  }
  
  componentDidMount() {
    this.fetchData();
  }
  
  componentDidUpdate(prevProps) {
    const props = this.props;
    
    if (props.sport !== prevProps.sport || props.league !== prevProps.league || props.id !== prevProps.id) {
      this.fetchData();
    }
  }
  
  fetchData() {
    const props = this.props;
    
    fetch('https://site.web.api.espn.com/apis/common/v3/sports/' + props.sport + '/' + props.league + '/athletes/' + props.id + '/stats')
    .then(resp => resp.json())
    .then(json => {
      if (props.sport === 'baseball') {
        for (let category of json.categories) {
          let str = category.displayName.toLowerCase().split('-');
          for (let i=0; i<str.length; i++) {
            str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
          }
          category.displayName = str.join(' ');
        }
      }
      
      if (this.state.selectType === 'stats') {
        this.updateChart({
          stats: json,
          select1: '0',
          select2: '0',
          select3: this.state.selects.stats[0].label
        });
      }
      else
        this.setState({stats: json});
    });
    
    fetch('https://site.web.api.espn.com/apis/common/v3/sports/' + props.sport + '/' + props.league + '/athletes/' + props.id + '/splits')
    .then(resp => resp.json())
    .then(json => {
      this.setState({splits: json});
      if (this.state.selectType === 'splits') {
        this.updateChart({
          splits: json,
          select1: '0',
          select2: '0',
          select3: this.state.selects.splits[0].label
        });
      }
      else
        this.setState({splits: json});
    });
  }
  
  changeSelectType(ev) {
    //this.setState({selectType: ev.target.value}, this.updateChart);
    this.updateChart({selectType: ev.target.value});
  }
  
  changeSelect1(ev) {
    //this.setState({select1: ev.target.value}, this.updateChart);
    console.log('change1', ev.target.selectedIndex, ev.target)
    this.updateChart({select1: ev.target.selectedIndex});
  }
  
  changeSelect2(ev) {
    //this.setState({select2: ev.target.value}, this.updateChart);
    this.updateChart({select2: ev.target.selectedIndex});
  }
  
  changeSelect3(ev) {
    //this.setState({select3: ev.target.value}, this.updateChart);
    this.updateChart({select3: ev.target.value});
  }
  
  
  updateChart(newStateData) {
    const props = this.props,
          state = this.state,
          metricGroup = newStateData.select3 || state.select3,
          catIdx = newStateData.hasOwnProperty('select1') ? newStateData.select1 : state.select1,
          statIdx = newStateData.hasOwnProperty('select2') ? newStateData.select2 : state.select2,
          type = newStateData.selectType || state.selectType,
          src = newStateData[type] || state[type],
          strokeWidth = (props.winWidth < 400) ? '2' : '3';
          //year = newStateData.select4 || this.state.select4,
          
    
          
    console.log('update', metricGroup, catIdx, statIdx, type, src, newStateData);
    
    let data = [];
    const leagueTeamData = teamData[props.sport][props.league];
    
    if (type === 'stats') {
      if (metricGroup === 'yoy-totals') {
        const statCat = src.categories[catIdx];
        
        const isStacked = (statCat.displayNames[statIdx].indexOf('Made-Attempted') !== -1);
        newStateData.isStacked = isStacked;
        
        if (isStacked) {
          newStateData.series = [ {color:'#c8102e'}, {color:'#1d428a'} ];
          data.push([
            'Season',
            statCat.displayNames[statIdx].replace('Made-Attempted', 'Made'),
            statCat.displayNames[statIdx].replace('Made-Attempted', 'Attempted')
          ]);
        }
        else {
          newStateData.series = null;
          data.push([
            'Season',
            statCat.displayNames[statIdx],
            { role: 'style' },
            { 'type': 'string', 'role': 'tooltip', 'p': {'html': true} },
            {type: 'string', role: 'annotation'}
          ]);
        }
        for (let yearData of statCat.statistics) {
          let team = leagueTeamData[yearData.teamId];
          //console.log('stroke-color: #' + team.altColor + '; stroke-width: 4; color: #' + team.color)
          if (isStacked) {
            const statArr = yearData.stats[statIdx].split('-');
            const made = parseFloat(statArr[0]);
            data.push([
              yearData.season.displayName,
              made,
              (parseFloat(statArr[1]) - made),
            ]);
          }
          else {
            const stat = parseFloat(yearData.stats[statIdx].replace(',', ''));
            data.push([
              yearData.season.displayName,
              stat,
              'stroke-color: #' + team.altColor + '; stroke-width: ' + strokeWidth + '; color: #' + team.color,
              '<div style="width:120px; padding:12px 8px 16px 8px;">' +
                '<img style="width:80px; display: block; margin:0 auto;" src="https://a.espncdn.com/combiner/i?img=/i/teamlogos/' + props.league + '/500/' + team.abbr + '.png&w=250&h=250">' +
                '<br>' +
                '<b>' + yearData.season.displayName + '</b>' +
                '<br><br>' +
                '<span>' + statCat.displayNames[statIdx] + ': <b>' + stat + '</b></span>' +
              '</div>',
              team.abbr
            ]);
          }
        }
      }
    }
    else if (type === 'splits') {
      if (metricGroup === 'game-by-game') {
        
      }
      else if (metricGroup === 'by-opp-team') {
        
      }
    }
    newStateData.data = data;
    console.log('chart new state', newStateData);
    this.setState(newStateData);
  }
  
  render() {
    const stats = this.props.stats,
          state = this.state,
          selectType = state.selectType,
          winWidth = this.props.winWidth;
          
    console.log('RENDER', state, this.props);
    
    const selectedType = state[selectType];
    const selectStyle = {background: 'white'};
    
    const select1Opts = (selectedType) ? selectedType.categories.map((cat, i) =>
      <option key={i} value={cat.name}>{cat.displayName}</option>
    ) : null;
    
    const select2Label = (state.selectType === 'stats') ? 'Stat' : 'Split';
    const select2Cat = (selectedType) ? selectedType.categories[state.select1] : null;
    const select2Opts = (selectedType) ? select2Cat.displayNames.map((item, i) =>
      <option key={i} value={select2Cat.names[i]}>{item}</option>
    ) : null;
    
    const select3Opts = (state.selects[selectType]) ? state.selects[selectType].map((item, i) =>
      <option key={i} value={item.label}>{item.title}</option>
    ) : null;
    
    console.log('select2 opts', select2Opts);
    
    return (
      <div>
        <div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'space-evenly', padding: '6px 24px 6px 24px'}}>
          <FormControl variant="outlined" style={{marginTop: 6, marginBottom: 12}}>
            <InputLabel htmlFor="select-type">Type</InputLabel>
            <Select
              native
              onChange={this.changeSelectType}
              style={selectStyle}
              label="Type"
              inputProps={{
                name: 'Type',
                id: 'select-type',
              }}
            >
              <option value="stats">Stats</option>
              <option value="splits">Splits</option>
            </Select>
          </FormControl>
          
          { select1Opts &&
            <FormControl variant="outlined" style={{marginTop: 6, marginBottom: 12}}>
              <InputLabel htmlFor="select-11">Category</InputLabel>
              <Select
                native
                onChange={this.changeSelect1}
                style={selectStyle}
                label="Category"
                inputProps={{
                  name: 'Category',
                  id: 'select-11',
                }}
              >{select1Opts}</Select>
            </FormControl>
          }
          
          {(winWidth < 768) && <br/>}
          
          { select2Opts &&
            <FormControl variant="outlined" style={{marginTop: 6, marginBottom: 12}}>
              <InputLabel htmlFor="select-2">{select2Label}</InputLabel>
              <Select
                native
                onChange={this.changeSelect2}
                style={selectStyle}
                label={select2Label}
                inputProps={{
                  name: select2Label,
                  id: 'select-2',
                }}
              >{select2Opts}</Select>
            </FormControl>
          }
          
          {(winWidth < 768) && <br/>}
          
          { select3Opts &&
            <FormControl variant="outlined" style={{marginTop: 6, marginBottom: 12}}>
              <InputLabel htmlFor="select-3">Metric</InputLabel>
              <Select
                native
                onChange={this.changeSelect3}
                style={selectStyle}
                label="Metric"
                inputProps={{
                  name: 'Metric',
                  id: 'select-3',
                }}
              >{select3Opts}</Select>
            </FormControl>
          }
        </div>
        
        { state.data && state.data.length &&
          <div style={{margin: 12, overflow: 'hidden', borderRadius: 10, border: '1px solid #cbccce', maxWidth: 1260, margin: '0 auto'}}>
            <Chart
              chartType="ColumnChart"
              loader={<div>Loading Chart...</div>}
              data={state.data}
              options={{
                animation: {
                  duration: 500,
                  easing: 'out',
                  startup: true,
                },
                annotations: {
                  textStyle: {
                    fontSize: 11,
                    bold: true,
                    auraColor: '#ff0000' // The color of the text outline.
                  }
                },
                chart: {
                  title: 'Company Performance',
                  subtitle: 'Sales, Expenses, and Profit: 2014-2017',
                },
                chartArea: {
                  width: '80%',
                  height: (winWidth < 1024) ? '70%' : '60%',
                  left: (winWidth < 1024) ? '12%' : '9%',
                  top: (winWidth < 1024) ? '11%' : '16%'
                },
                height: (winWidth < 400) ? 280 : 350,
                isStacked: state.isStacked,
                legend: 'none',
                series: state.series,
                tooltip: { isHtml: true }
              }}
              // For tests
              rootProps={{ 'data-testid': '2' }}
            />
          </div>
        }
      </div>
    )
  }
}

export default ChartPanel;