import React from 'react'
import state_lookup from '../state_lookup'
import saveAs from 'browser-saveas'
import csvStringify from 'csv-stringify'

const SR_REGEXP = /(Sr|Jr|I|II|III|IV)\.?$/i

export default class OrderList extends React.Component {
  constructor(props) {
    super()
    this.downloadCsv = this.downloadCsv.bind(this)
  }
  downloadCsv() {
    const orders = this.parseOrders().map((order) => {
      let name = order.order_ship_name.replace(/&quot/g,'\"').split(" ")
      let lastName = name.pop()
      if (lastName.match(SR_REGEXP)) {
        lastName = name.pop() + " " + lastName
      }
      const firstName = name.join(" ")
      const date_partz = order.order_date.split("T")
      const date = date_partz[0]
      const time = date_partz[1].replace(/\:\d\d\.\d\d\dZ/,"")
      return [
        order.order_id,
        date,
        time,
        order.order_checkout_type,
        firstName,
        lastName,
        (order.order_company && order.order_company !== order.order_ship_name) ? order.order_company : "",
        order.order_address1,
        order.order_address2,
        order.order_city,
        state_lookup(order.order_state),
        order.order_zip,
        order.order_country !== 'United States' ? '' : order.order_country,
        order.order_email,
      ]
    })
    csvStringify(orders, (err, csv) => {
      const blob = new Blob([csv], {type : 'text/plain;charset=utf-8'})
      saveAs(blob, this.props.product.product_name.replace(/\s+/g,"") +'.csv')
    })
  }
  parseOrders() {
    return this.props.orders.filter( (order) => {
      // also filter where order.order_status == 3 (paid in full) ?
      // filter weird blank orders if found
      return !! order.order_ship_name && (order.order_status == 3 || order.order_status == 4)
    }).map( (order, i) => {
      const name = order.order_ship_name
        .toUpperCase()
        .replace(SR_REGEXP, "")
        .split(" ")
        .reverse()[0]
      return [ name, order ]
    }).sort((a,b) => {
      return a[0] < b[0] ? -1 : a[0] === b[0] ? 0 : 1
    }).map((pair, i) => {
      return pair[1]
    })
  }
  render() {
    if (! this.props.product) {
      return ( <div></div> )
    }
    if (! this.props.orders) {
      return ( <div className='loading'>Loading...</div> )
    }
    if (! this.props.orders.length) {
      return ( <div className='notfound'>No orders found</div> )
    }

    const items = this.parseOrders().map((order, i) => {
      const order_link = (
        <a href={'http://shopping.msana.com/cw4/admin/order-details.php?order_id=' + order.order_id} target='_blank'>
          (order)
        </a>
      )
      const customer_link = order.order_checkout_type === 'guest' ? '' : (
        <a href={'http://shopping.msana.com/cw4/admin/customer-details.php?customer_id=' + order.order_customer_id} target='_blank'>
          (customer)
        </a>
      )
      let order_name, order_address
      if (order.order_company && order.order_company !== order.order_ship_name) {
        order_name = (
          <span>
            {order.order_ship_name.replace(/&quot/g,'\"')}<br />
            {order.order_company}
          </span>
        )
      }
      else {
        order_name = order.order_ship_name
      }
      if (order.order_address2 && order.order_address2 !== order.order_address1) {
        order_address = (
          <span>
            {order.order_address1}<br />
            {order.order_address2}
          </span>
        )
      }
      else {
        order_address = order.order_address1
      }
      const order_email = ! order.order_email ? '' : (
        <a className='email' href={'mailto:'+order.order_email}>{order.order_email}</a>
      )
      
      const country = order.order_country !== 'United States' ? order.order_country : ""
      return (
        <div key={i}>
          <div>
            {order_link} {customer_link}
          </div>
          <div>
            {order_name}<br />
            {order_address}<br />
            {order.order_city}, {state_lookup(order.order_state)} {order.order_zip} {country}<br/>
            {order_email}
          </div>
        </div>
      )
    })
    
    return (
      <div className='orderList'>
        <a href='#' onClick={() => this.downloadCsv()}>Download CSV</a>
        {items}
        <br />
        <br />
        <br />
      </div>
    )
  }
}