import React, { Component } from 'react';

import ChartPanel from './chart-panel.jsx';
import Card from '@material-ui/core/Card';

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

const brightnessRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;

export class AthletePanel extends Component {
  constructor(props) {
    super();
    this.state = { winWidth: 0, currTeamData: null };
    this.updateDimensions = this.updateDimensions.bind(this);
    this.callShowTeam = this.callShowTeam.bind(this);
  }
  
  callShowTeam(ev) {
    const info = this.props.info,
          league = info.leagueInfo.abbreviation.toLowerCase(),
          team = teamData[info.type][league][info.team.id];
    team.sport = info.type;
    team.league = league;
    console.log('click', team, this.state.currTeamData, info);
    this.props.showTeam(team);
  }
  
  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
    this.updateDimensions();
  }
  
  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }
  
  updateDimensions() {
    this.setState({ winWidth: window.innerWidth });
  }
  
  colorBrightness(hex) {
    const result = brightnessRegex.exec(hex);
    return result ? (0.2126*parseInt(result[1], 16) + 0.7152*parseInt(result[2], 16) + 0.0722*parseInt(result[3], 16)) : null;
  }
  
  render() {
    const props = this.props;
    const winWidth = this.state.winWidth;
    
    const info = props.info;
    
    const {
      displayJersey, displayDraft, status, team, statsSummary, type
    } = info;
    
    const league = info.leagueInfo.abbreviation.toLowerCase();
    
    let displayHeight, displayWeight, dob, dobArr, ageDate;
    let id, name, position, height, weight, dateofbirth, college;
    
    const collegeAID = info.hasOwnProperty('collegeAthlete') ? info.collegeAthlete.id : null;
    
    id = info.id;
    name = {
      first: info.firstName,
      last: info.lastName,
      display: info.displayName
    };
    position = info.position.abbreviation;
    displayHeight = info.displayHeight;
    displayWeight = info.displayWeight;
    dobArr = info.displayDOB.split('/');
    dob = parseInt(dobArr[1]) + '/' + parseInt(dobArr[0]) + '/' + dobArr[2];
    ageDate = dobArr[2] + '-' + dobArr[1] + '-' + dobArr[0];
    college = info.college;
    
    console.log('info', props.info);
    
    
    let statusClass = (status.name !== 'Active' && status.name !== '') ? 'TextStatus TextStatus--red plain ml0' : 'TextStatus TextStatus--green plain ml0';
    
    const headshotHref = (type !== 'soccer') ? 'https://a.espncdn.com/combiner/i?img=/i/headshots/' + league + '/players/full/' + id + '.png&w=250'
                                             : 'https://a.espncdn.com/combiner/i?img=/i/headshots/' + type + '/players/full/' + id + '.png&w=250';
    const age = Math.abs(new Date(Date.now() - new Date(ageDate)).getUTCFullYear() - 1970);
    
    let teamLogoHref = '';
    if (status.id) {
      if (status.id !== '2')
        teamLogoHref = 'https://a.espncdn.com/combiner/i?img=/i/teamlogos/' + league + '/500/' + team.abbreviation + '.png&w=250&h=250';
      else
        teamLogoHref = 'https://a.espncdn.com/combiner/i?img=/i/teamlogos/leagues/500/' + league + '.png&w=250&h=250';
    }
    
    let contract, contractKeys;
    try {
      console.log('leagueis', league, info);
      contract = props.contracts[league][team.slug][name.display];
      contractKeys = props.contracts[league].titles;
      //console.log('gotContract', contract);
    }
    catch(err) {
      contract = null;
      console.error('gotContract error', league, err);
    }
    let showContract = (!!contract && winWidth > 1260);
    console.log('contract', showContract, contract);
    
    console.log('statssummary');
    console.log(statsSummary);
    
    const keyStatStyleTop = showContract ? {width: '50%', paddingBottom: 12} : {};
    const keyStatStyleBottom = showContract ? {width: '50%'} : {};
    const keyStatItems = (statsSummary.statistics) ? statsSummary.statistics.map((stat, i) =>
      <li key={stat.abbreviation} className="flex-expand" style={(i < 2) ? keyStatStyleTop : keyStatStyleBottom}>
				<div className="StatBlockInner flex-expand">
					<div className="StatBlockInner__Label tc clr-gray-04 n9" title={ stat.displayName }>{ stat.abbreviation }</div>
					<div className="StatBlockInner__Value tc fw-medium n3 clr-gray-02">{ stat.displayValue }</div>
					{!showContract && <div className="StatBlockInner__Position tc clr-gray-04 n9" title="Rank">{ stat.rankDisplayValue }</div>}
				</div>
			</li>
    ) : '';
    
    let wrapClass = 'PlayerHeader w-100 overflow-hidden';
    if (winWidth > 1024)
      wrapClass += ' PlayerHeader--desktop';
    else if (winWidth > 768)
      wrapClass += ' PlayerHeader--tablet';
    else
      wrapClass += ' PlayerHeader--mobile';
      
    let containerClass = 'PlayerHeader__Container w-100 center flex relative';
    if (winWidth > 1024)
      containerClass += ' items-center justify-between';
    else
      containerClass += ' flex-column';
      
    let currTeamData, lighterColor = 'FFFFFF4d', darkerColor = '000000';
    try {
      currTeamData = teamData[type][league][team.id];
      this.state.currTeamData = currTeamData;
      
      let primaryBrightness = this.colorBrightness(currTeamData.color);
      let alternateBrightness = this.colorBrightness(currTeamData.altColor);
      console.log('color brightnesses', primaryBrightness, alternateBrightness);
      
      if (Math.max(primaryBrightness, alternateBrightness) < 50) {
        darkerColor = currTeamData.color;
      }
      else if (primaryBrightness > alternateBrightness) {
        lighterColor = currTeamData.color + 'b3';
        darkerColor = currTeamData.altColor;
      }
      else {
        lighterColor = currTeamData.altColor + 'b3';
        darkerColor = currTeamData.color;
      }
    }
    catch(e) {
      console.error(e, type, league, id, teamData);
    }
    
    console.log('teamis', team);
    
    return (
      <Card raised={true} style={{maxWidth: 1260, marginTop: 6, marginLeft: 'auto', marginRight: 'auto'}}>
        <div className={wrapClass} style={{backgroundColor: '#' + lighterColor}}>
          <div className={containerClass}>
          	<div className="PlayerHeader__Left flex items-center justify-start overflow-hidden bb brdr-clr-gray-09">
          		<div className="PlayerHeader__Main flex items-center">
          			<div className="PlayerHeader__Image_Container overflow-hidden bg-clr-gray-09">
          				<div className="PlayerHeader__Image">
          					<figure className="Image aspect-ratio--parent PlayerHeader__Logo">
          						<div className="RatioFrame aspect-ratio--1x1"></div>
          						<div className="Image__Wrapper aspect-ratio--child">
          						  <img className="" alt={ team.displayName } src={ teamLogoHref } onError={e => e.target.style.display='none'} onLoad={e => e.target.style.display='block'} />
          						</div>
          					</figure>
          					<div className="PlayerHeader__Overlay_Detail"></div>
          					<div className="PlayerHeader__Overlay PlayerHeader__Overlay--right"></div>
          					<figure className="Image aspect-ratio--parent PlayerHeader__HeadShot">
          						<div className="RatioFrame aspect-ratio--auto"></div>
          						<div className="Image__Wrapper Image__Wrapper--relative">
          							<img className="" alt={ name.display } src={ headshotHref } onError={e => e.target.style.display='none'} onLoad={e => e.target.style.display='block'} />
          						</div>
          					</figure>
          					<div className="PlayerHeader__Overlay PlayerHeader__Overlay--right PlayerHeader__Overlay--opaque"></div>
          				</div>
          				<div className="PlayerHeader__Overlay PlayerHeader__Overlay--left"></div>
          			</div>
          			<div className="PlayerHeader__Main_Aside min-w-0 flex-grow flex-basis-0">
          				<h1 className="PlayerHeader__Name flex flex-column ttu fw-bold pr4 h3">
          					<span className="truncate min-w-0 fw-light">{ name.first }</span>
          					<span className="truncate min-w-0">{ name.last }</span>
          				</h1>
          				<div className="PlayerHeader__Team n8 mt3 mb4 flex items-center mt3 mb4 clr-gray-01">
          					<img className="Image Logo Logo__sm" alt={ team.displayName } title={ team.displayName } src={ teamLogoHref }
          					     onError={e => e.target.style.display='none'} onLoad={e => e.target.style.display='block'} />
          					
          					{ (status.id === '2') ?
          					  <ul className="PlayerHeader__Team_Info list flex pt1 pr4 min-w-0 flex-basis-0 flex-shrink flex-grow nowrap">
            						<li>{ position }</li>
          					  </ul>
          					  :
          					  <ul className="PlayerHeader__Team_Info list flex pt1 pr4 min-w-0 flex-basis-0 flex-shrink flex-grow nowrap">
            						<li className="truncate min-w-0">
            							<a className="AnchorLink clr-black" tabIndex="0" onClick={this.callShowTeam}>{ team.name }</a>
            						</li>
            						<li>{ displayJersey }</li>
            						<li>{ position }</li>
          					  </ul>
          					}
          				</div>
          				{ (winWidth <= 768) &&
          				  <div className="PlayerHeader__Bio mb4">
          				    <div className="flex brdr-clr-gray-07 n9 brdr-clr-gray-07">
          				      <ul className="PlayerHeader__Bio_List flex flex-column PlayerHeader__Bio_List--small list">
          				        <li>
          				          <div className="ttu">HT/WT</div>
          				          <div className="fw-medium clr-black">{ displayHeight + ', ' + displayWeight }</div>
          				        </li>
          				        <li>
          				          <div className="ttu">DOB</div>
          				          <div className="fw-medium clr-black">{ dob + ' (' + age + ')' }</div>
          				        </li>
          				        <li>
          				          <div className="ttu">College</div>
          				          <div className="fw-medium clr-black">{ !!college ? college.name : 'N/A'  }</div>
          				        </li>
          				      </ul>
          				    </div>
          				  </div>
          				}
          			</div>
          		</div>
          		{ (winWidth > 768) &&
            		<div className="PlayerHeader__Bio pv5">
            			<div className="flex brdr-clr-gray-07 pl4 bl bl--dotted n8 brdr-clr-gray-07">
            				<ul className="PlayerHeader__Bio_List flex flex-column list">
            					<li>
            						<div className="ttu">HT/WT</div>
            						<div className="fw-medium clr-black">{ displayHeight + ', ' + displayWeight }</div>
            					</li>
            					<li>
            						<div className="ttu">DOB</div>
            						<div className="fw-medium clr-black">{ dob + ' (' + age + ')' }</div>
            					</li>
            					<li>
            						<div className="ttu">College</div>
            						<div className="fw-medium clr-black">{ !!college ? college.name : 'N/A'  }</div>
            					</li>
            					<li>
            						<div className="ttu">Draft Info</div>
            						<div className="fw-medium clr-black">{ displayDraft }</div>
            					</li>
            					<li>
            						<div className="ttu">Status</div>
            						<div className="fw-medium clr-black">
          								<span className={ statusClass }>{ status.name }</span>
            						</div>
            					</li>
            				</ul>
            			</div>
            		</div>
          		}
          		{ (winWidth > 1260 && showContract) &&
            		<div className="PlayerHeader__Bio pv5" style={{marginLeft: 36}}>
            			<div className="flex brdr-clr-gray-07 pl4 bl bl--dotted n8 brdr-clr-gray-07">
            				<ul className="PlayerHeader__Bio_List flex flex-column list">
              				{
              				  contract.map((item, i) =>
                          <li>
                						<div className="ttu">{ contractKeys[i] }</div>
                						<div className="fw-medium clr-black">{ item }</div>
                					</li>
                        )
              				}
            				</ul>
            			</div>
            		</div>
          		}
          	</div>
          	{ !!statsSummary.statistics &&
            	<div className="PlayerHeader__Right flex align-center pa4" style={{paddingRight: (winWidth > 1024) ? 16 : 12}}>
            		<aside className="StatBlock br-5 ba overflow-hidden flex-expand StatBlock--multiple bg-clr-white brdr-clr-gray-06 PlayerHeader__StatBlock" style={showContract ? {width: 200} : {}}>
            			<h2 className="StatBlock__Header tc ttu clr-white h9 pv2 ph2 truncate list" style={{ background: '#' + darkerColor, color: '#ffffff' }}>{ statsSummary.displayName }</h2>
            			<ul className="StatBlock__Content flex list ph4 pv3 justify-between" style={showContract ? {flexWrap: 'wrap'} : {}}>
            				{ keyStatItems }
            			</ul>
            		</aside>
            	</div>
          	}
        	</div>
        </div>
        <div style={{paddingTop: (winWidth > 1024) ? 12 : 0, position: 'relative', zIndex: 1}}>
          <ChartPanel sport={type} league={league} id={id} winWidth={winWidth} college={college} collegeAID={collegeAID} team={team} />
        </div>
      </Card>
    )
  }
}

export default AthletePanel;