import DatePicker from 'react-datepicker';
import moment from 'moment';
import numeral from 'numeral';
import OrderDetails from './orderDetails.jsx';
import OrderPart from './orderpart.jsx';
import React from 'react';
import SpotTableRow from './spotTableRow.jsx';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { PORTAL_API_PATH } from '../constants/appConstants';
import { spotsByOrder, spotsByOrderPart } from '../actions/campaignActions';

class SpotTable extends React . Component {
  /** */
  constructor(props) {
    super(props);
    this.state = {
      startDate: moment(),
      endDate: moment()
    };
  }

  /** */
  componentWillMount() {
    let { medium, orderId, orderPartId} = this.props.params;
    // let now = this.state.startDate;
    // let dateFrom = `${this.state.startDate.format('YYYY-MM-DD')}`;
    // let dateTo = `${this.state.endDate.format('YYYY-MM-DD')}`;

    if(orderPartId) {
      this.props.dispatch(spotsByOrderPart(medium, orderId, orderPartId, '17-11-1858', '17-11-1858'));
    }
    else {
      this.props.dispatch(spotsByOrder(medium, orderId, '17-11-1858', '17-11-1858'));
    }
  }

  /** */
  componentDidUpdate(prevProps, prevState) {
    let { spots } = this.props;
    let spotData = spots.get('data');
    let { medium, orderId, orderPartId } = this.props.params;

    if(spotData) {
      let minDate = moment(orderPartId ? spotData.orderParts[0].orderPartStartDate : spotData.orderStartDate);
      let maxDate = moment(orderPartId ? spotData.orderParts[0].orderPartEndDate : spotData.orderEndDate);
      let selectedStartDate = this.state.startDate;
      let selectedEndDate = this.state.endDate;

      if(maxDate.isBefore(selectedEndDate) || minDate.isAfter(selectedStartDate)) {
        this.handleStartDateChange(minDate);
        this.handleEndDateChange(maxDate);
      }
      if(this.state.startDate.format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
        this.setState({
          startDate: minDate,
          endDate: maxDate
        });
      }
    }
  }

  /**
   */
  handleStartDateChange(startDate) {
    this.setState({
      startDate: startDate
    });
    let { medium, orderId, orderPartId } = this.props.params;
    if(orderPartId) {
      this.props.dispatch(spotsByOrderPart(medium, orderId, orderPartId, startDate.format('YYYY-MM-DD'),
                                           this.state.endDate.format('YYYY-MM-DD')));
    }
    else {
      this.props.dispatch(spotsByOrder(medium, orderId, startDate.format('YYYY-MM-DD'),
                                           this.state.endDate.format('YYYY-MM-DD')));
    }
  }
    /**
   */
  handleEndDateChange(endDate) {
    this.setState({
      endDate: endDate
    });
    let { medium, orderId, orderPartId } = this.props.params;
    if(orderPartId) {
      this.props.dispatch(spotsByOrderPart(medium, orderId, orderPartId,
                                       this.state.startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')));
    }
    else {
      this.props.dispatch(spotsByOrder(medium, orderId,
                                       this.state.startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')));
    }
  }

  /**
   * Render method;
   * Datepicker via https://hacker0x01.github.io/react-datepicker/
   * Daar staat veel uitleg over het betreffende object
   */
  render() {
    let { spots } = this.props;
    let { medium, orderId, orderPartId } = this.props.params;
    let spotData = spots.get('data');
    if(!spotData) {
      return (<div className="listContent">
        <p>Geen uitzendschema gevonden.</p>
      </div>);
    }

    let spotArray = spotData.spots;
    let pdfUrl = orderPartId ? `${orderId}/${orderPartId}` : `${orderId}`;

    let order = {
      orderBudget: spotData.orderBudget,
      orderEndDate: spotData.orderEndDate,
      orderId: spotData.orderId,
      orderStartDate: spotData.orderStartDate,
      productDescr: spotData.productDescr,
      productId: spotData.productId,
      totalReqGrp: spotData.totalReqGrp,
      totalBookedGrp: spotData.totalBookedGrp,
      totalReqBudget: spotData.totalReqBudget,
      totalBookedBudget: spotData.totalBookedBudget,
    };

    let minDate = moment(orderPartId ? spotData.orderParts[0].orderPartStartDate : spotData.orderStartDate);
    let maxDate = moment(orderPartId ? spotData.orderParts[0].orderPartEndDate : spotData.orderEndDate);
    console.log('Maxdate ' + spotData.orderParts[0].orderPartEndDate + '  ' + spotData.orderEndDate);
    let orderPartBlock = null;
    if(orderPartId) {
      orderPartBlock = (<OrderPart order={spotData.orderParts[0]} showUitzendschemaLink={false} />);
    }

    let spotList = (<div className="spotList">
      <p>Geen spots gevonden voor deze datum.</p>
    </div>);
    if(spotArray.length > 0) {
      spotList = (<div className="spotList">
        {spotArray.map((s) => {
          return (<SpotTableRow key={s.spotId} orderId={orderId} spot={s} />);
        })}
      </div>);
    }

    return (<div className="listContent">
      <OrderDetails advertiserName={spotData.advertiserName} order={order} />

      <div className="tablist">
        <Link to={`campaigns/${medium}/${orderId}`}>Campagne in detail</Link>
        <Link className="active" to={`campaigns/${medium}/spots/${orderId}`}>
               {orderPartId ? 'Uitzendschema van deelorder: ' + spotData.orderParts[0].packageDescr :
                                                 'Totale Uitzendschema'}</Link>
        { medium === 'radio' ? <Link to={`campaigns/${medium}/summary/${orderId}`}>Samenvatting</Link> : null }
      </div>

      {orderPartBlock}

      <div className="uitzendschemaToolbar">
        <div className="datePicker">
          <label>Datum van:</label>
          <DatePicker dateFormat="DD-MM-YYYY" todayButton="Vandaag"
            placeholderText="Kies een datum" locale="nl-nl"
            minDate={minDate}
            maxDate={maxDate > minDate ? maxDate.subtract(1, 'day') : maxDate}
            selected={this.state.startDate} onChange={this.handleStartDateChange.bind(this)} />
        </div>
        <div className="datePicker">
          <label>tot</label>
          <DatePicker dateFormat="DD-MM-YYYY" todayButton="Vandaag"
            placeholderText="Kies een datum" locale="nl-nl"
            minDate={minDate}
            maxDate={maxDate > minDate ? maxDate.subtract(1, 'day') : maxDate}
            selected={this.state.endDate} onChange={this.handleEndDateChange.bind(this)} />
        </div>
        <div className="downloadText">
          <label>Download volledige schema als:</label>
          <div className="downloadBtn">
            <a target="_blank" href={`${PORTAL_API_PATH}/spots/${pdfUrl}.pdf`}>
              PDF
            </a>
          </div>
          <div className="downloadBtn">
            <a target="_blank" href={`${PORTAL_API_PATH}/spots/${pdfUrl}.xls`}>
              Excel
            </a>
          </div>
        </div>
      </div>

      <div className="spotTotals">
        <div className="spotTotal">
          <span className="labelTxt">Totale bruto spotprijs: </span>
          <span className="valueTxt">{numeral(spotData.totalBookedBudget).format('$ 0,000.00')}</span>
        </div>
        <div className="labelTxt geselecteerd">Geselecteerd: </div>
        <div className="price">
          <div className="bruto">
            <span className="labelTxt">Bruto spotprijs: </span>
            <span className="valueTxt">{orderPartId ?
                                    numeral(spotData.orderParts[0].totalGrossSpotPrice).format('$ 0,000.00') :
                                    numeral(spotData.totalGrossSpotPrice).format('$ 0,000.00')}</span>
          </div>
          <div className="netto">
            <span className="labelTxt">Netto spotprijs: </span>
            <span className="valueTxt">{orderPartId ?
                                    numeral(spotData.orderParts[0].totalNettSpotPrice).format('$ 0,000.00') :
                                    numeral(spotData.totalNettSpotPrice).format('$ 0,000.00')}</span>
          </div>
        </div>
      </div>
      {spotList}
    </div>);
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    spots: state.spots
  };
};

export default connect(mapStateToProps)(SpotTable);
