var React = require('react'),
    CartStore = require('../../stores/cartStore'),
    AddToCart = require('../cart/addToCart'),
    CartActions = require('../../actions/cartActions'),
    NavigationActions = require('../../actions/navigationActions'),
    SingleItem = require('../items/singleItem'),
    Globals = require('../../globals'),
    LinkBanner = require('../linkBanner/linkBanner'),
    CartTotal = require('./cartTotal');
    AllItemsInGroup = require('../items/allItemsInGroup');


var Router = require('react-router');

var CartPage = React.createClass({
    _onTakeItemOut: function(itemId) {
      CartActions.takeItemOut(itemId);
    },
    _goToStartPage: function() {
      NavigationActions.goToHome();
    },

    render: function() {
      var counts = this.state.itemCounts;
      var self = this;
      var displayedItems = this.state.items.filter(function(i) {
        if(!counts) return false;
         var count = counts[i.get('id')].get('count');
         return count > 0 || count === "";
        }); // tableDetails

      var displayedItemsDesktop = displayedItems.map( this.desktopDetails );
      var displayedItemsMobile = displayedItems.map( this.mobileDetails );

      var deliveryDestination = (<span></span>);

      if (this.state.destinationValid) {
        deliveryDestination = (
            <div>
               Na adresu {this.state.deliveryDestination.name},
            </div>
          )
      }

      var cartTotal = (
        <div>

        <div className="row cart-total">
          <div className="col-lg-6">Roba:<br />Dostava:<br />Ukupno:</div>
           <div className="col-lg-6 text-right">

             <CartTotal items={this.state.items} itemCounts={this.state.itemCounts} /><br />
             <span className={this.state.deliveryDestinationErrors['place'] ? 'hidden' : 'shown'}>
              <CartTotal deliveryCosts={this.state.deliveryCosts} instantDelivery={this.state.deliveryDestination.get('instant_delivery')}/><br />
              <CartTotal items={this.state.items} itemCounts={this.state.itemCounts} deliveryCosts={this.state.deliveryCosts} instantDelivery={this.state.deliveryDestination.get('instant_delivery')}/>
              </span>
           </div>
        </div>
     
        <div className="row">
           <div className="col-lg-12 pull-left">
              <button className="mybutton" onClick={this._onOrderClick}>Završi narudžbu</button> ili <button className="btn btn-default" onClick={this._goToStartPage}>Nastavi kupovati</button> 
           </div>

        </div>
        </div>
      );

      var instantDelivery = (<div className="text-center">
            <input type="checkbox" 
                checked={this.state.deliveryDestination.get('instant_delivery')}  onChange={this._onInstantDeliveryChange}/>  
                 {" Hitna dostava (ako naručite toku radnog dana do 16h) ili ujutru (ako naručite poslije 16h)"}
        </div>);

      var buySomethingMessage = (<div></div>);
      var content;

      if (displayedItems.length <= 0) {
        cartTotal = (<div></div>)
        buySomethingMessage = (<div>
             <div className="text-primary">Nemate ni jedan artikal u vašoj korpi. Kada vidite nešto što vam se sviđa - pritisnite dugme UBACI U KORPU pored artikla kako biste ga dodali u korpu.</div>
             <div>Evo nekoliko artikala koje vam možemo preporučiti: </div>
             <AllItemsInGroup groupId={Globals.ItemGroupIdOfEmptyCartPage} />

          </div>)
        content = buySomethingMessage;
      } else {
        content = (<div>
           <table className="table">
             <thead className="hidden-md hidden-sm hidden-xs">
               <tr className="text-center">
                 <th className="col-lg-2"></th>
                 <th>Proizvod</th>
                 <th>Cijena</th>
                 <th className="col-lg-1">Količina</th>
                 <th className="hidden-md hidden-sm hidden-xs">Ukupna cijena</th>
                 <th></th>
               </tr>
             </thead>
             <tbody>
               {displayedItemsMobile}
               {displayedItemsDesktop}
             </tbody>
           </table>
           {buySomethingMessage}
           
           {cartTotal}
        </div>)
      }

      return (

        <div className="col-lg-12">
        <div className="row">
          <div className="col-lg-12">
            <LinkBanner locationName="checkoutPage"/>
          </div>
        </div>
        <div className="row">
           <div className="col-lg-12">
             <div className="cart-title">KORPA</div>
             {content}
           </div>
        </div>
        </div>
        );

    },

    desktopDetails: function (i) {
        var self = this;
        var counts = this.state.itemCounts;
        var count = counts[i.get('id')].get('count');
        var commission = counts[i.get('id')].get('commission');
        var price = i.get('list_price');
        var firstImage = i.get('multi_media_descriptions')[0];
        firstImage = firstImage || { resized_url:  "https://res.cloudinary.com/lfvt7ps2n/image/upload/c_fit,h_172,w_226/v1421732950/http_www.asms.ru_bitrix_templates_main_images_nophoto_irnofq.png" } ;
        return (
          <tr key={i.get('id') } className="cart-table-row hidden-md hidden-xs hidden-sm">
            <td className='text-center'>
              <img style={{maxWidth: '90px', maxHeight: '90px'}} src={firstImage.url} alt="product image"/>
            </td>
            <td className="cart-price-bigger">
              <p> {i.get('brand').name}</p>
              <p>
                {i.get('name')}
              </p>
               </td>
                <td className="cart-price-bigger text-center"> <abbr title={ Globals.FormatPercentage(commission) + " RUC"}>{ Globals.FormatCurrency(price) } </abbr>
             </td>
            <td >
              <select style={{textAlign: 'center'}} value={count} className="form-control"
                onChange={self._onQuantityChange.bind(self, i.get('id'))}
                >

                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
              </select>
            </td>
            <td className="cart-price-bigger text-center">
                { Globals.FormatCurrency(count * price) }
            </td>
            <td>
              <button className="btn btn-default" onClick={self._onTakeItemOut.bind(self, i.get('id'))}>Ukloni iz korpe</button>
            </td>
          </tr>) 
      }, 

    mobileDetails: function (i) {
        var self = this;
        var counts = this.state.itemCounts;
        var count = counts[i.get('id')].get('count');
        var commission = counts[i.get('id')].get('commission');
        var price = i.get('list_price');
        var firstImage = i.get('multi_media_descriptions')[0];
        firstImage = firstImage || { resized_url:  "https://res.cloudinary.com/lfvt7ps2n/image/upload/c_fit,h_172,w_226/v1421732950/http_www.asms.ru_bitrix_templates_main_images_nophoto_irnofq.png" } ;
        return (
          <tr key={i.get('id') } className="cart-table-row hidden-lg">
            <td className="cart-price-bigger">
              <p> {i.get('brand').name}</p>
              <p>
                {i.get('name')}
              </p>
              <p>
              <details>
              <summary>
              { Globals.FormatCurrency(price) }
              </summary>
                <div className="cart-commision-tiny text-left">{ Globals.FormatPercentage(commission) } RUC</div>
                </details>
               </p>
            </td>
            <td className="col-sm-2 col-xs-2 col-md-2">
              <select style={{textAlign: 'center'}} value={count}
                onChange={self._onQuantityChange.bind(self, i.get('id'))}
                >

                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
              </select>
            </td>
            <td>
              <button onClick={self._onTakeItemOut.bind(self, i.get('id'))}>X</button>
            </td>
          </tr>) 
      }, 

    // Add change listeners to stores
    componentDidMount: function() {
      CartStore.addChangeListener(this._onChange);
      CartActions.load();
    },

    componentWillUnmount: function () {
      CartStore.removeChangeListener(this._onChange);
    },

    _onChange: function () {
         if (this.isMounted()) {
             this.setState(CartStore.getWholeCartState());
        }

    },

    _onInstantDeliveryChange: function () { 
      CartActions.changeDeliveryDestinationProperty("instant_delivery", !this.state.deliveryDestination.get('instant_delivery'));
     },
    _onOrderClick: function () {
      NavigationActions.goToCheckout();
    },
    _onQuantityChange: function(itemId, e) {
      CartActions.setItemCount(itemId, e.target.value);
    },
    getInitialState: function () {
      return CartStore.getWholeCartState();
    }
});


module.exports = CartPage;
