import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html, LitElement } from 'lit-element'

class PickupLogisticsPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _searchFields: Array,
      orderInformation: Object,
      pickupConfig: Object,
      timeslotConfig: Object,
      data: Object,
      timeSlotData: Object,
      _selectedRecords: Array
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .button-container {
          padding: var(--button-container-padding);
          margin: var(--button-container-margin);
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
          height: var(--button-container-height);
        }
        [danger] {
          --mdc-theme-primary: var(--mdc-danger-button-primary-color);
        }
      `
    ]
  }

  render() {
    return html`
      <div class="grist-container">
        <div class="grist">
          <h2>${i18next.t('label.address_info')}</h2>
          <data-grist
            id="logisticsPickup"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.pickupConfig}
            .fetchHandler="${this.fetchHandler.bind(this)}"
            @select-record-change=${e => this.fetchTimeSlot(e.detail.records)}
          ></data-grist>
        </div>

        <div class="grist">
          <h2>${i18next.t('label.timeslot_info')}</h2>
          <data-grist
            id="timeslotPickup"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.timeSlotConfig}
            .data="${this.timeSlotData}"
          ></data-grist>
        </div>
      </div>

      <div class="button-container">
        <mwc-button
          raised
          danger
          label="${i18next.t('button.cancel')}"
          @click=${() => {
            history.back()
          }}
        >
        </mwc-button>
        <mwc-button @click=${this._selectPickup.bind(this)} raised label="${i18next.t('button.confirm')}"></mwc-button>
      </div>
    `
  }

  updated(changes) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  firstUpdated() {
    this.pickupConfig = {
      rows: {
        selectable: {
          multiple: false
        },
        appendable: false
      },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: false },
        {
          type: 'string',
          name: 'addressId',
          header: i18next.t('field.address_id'),
          width: 100
        },
        {
          type: 'string',
          name: 'country',
          header: i18next.t('field.country'),
          width: 80
        },
        {
          type: 'string',
          name: 'state',
          header: i18next.t('field.state'),
          width: 120
        },
        {
          type: 'string',
          name: 'city',
          record: { align: 'left' },
          header: i18next.t('field.city'),
          width: 120
        },
        {
          type: 'string',
          name: 'address',
          record: { align: 'left' },
          header: i18next.t('field.address'),
          width: 200
        },
        {
          type: 'string',
          name: 'zipcode',
          header: i18next.t('field.zipcode'),
          width: 120
        },
        {
          type: 'string',
          name: 'district',
          header: i18next.t('field.district'),
          width: 120
        },
        {
          type: 'string',
          name: 'town',
          record: { align: 'left' },
          header: i18next.t('field.town'),
          width: 120
        }
      ]
    }

    this.timeSlotConfig = {
      rows: {
        selectable: {
          multiple: false
        },
        appendable: false
      },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: false },
        {
          type: 'string',
          name: 'pickupTimeId',
          header: i18next.t('field.pickup_time_id'),
          width: 100
        },
        {
          type: 'date',
          name: 'pickupDate',
          header: i18next.t('field.date'),
          width: 80
        },
        {
          type: 'string',
          name: 'timeText',
          record: { align: 'left' },
          header: i18next.t('field.description'),
          width: 120
        }
      ]
    }
  }

  get logisticsPickupGrist() {
    return this.shadowRoot.querySelector('data-grist#logisticsPickup')
  }

  get timeslotPickupGrist() {
    return this.shadowRoot.querySelector('data-grist#timeslotPickup')
  }

  async fetchHandler() {
    const response = await client.query({
      query: gql`
        query getAddressList($storeId: String!) {
          getAddressList(storeId: $storeId) {
            addressId
            country
            state
            city
            address
            zipcode
            district
            town
            addressFlag
          }
        }
      `,
      variables: {
        storeId: this.orderInformation.marketplaceStore.id
      }
    })

    if (!response.errors) {
      return {
        records: response.data.getAddressList || []
      }
    }
  }

  async fetchTimeSlot(selectedAddressRecord) {
    const selectedAddressId = selectedAddressRecord.map(record => record.addressId)[0]
    const response = await client.query({
      query: gql`
        query getTimeSlot($storeId: String!, $orderNo: String!, $addressId: String!) {
          getTimeSlot(storeId: $storeId, orderNo: $orderNo, addressId: $addressId) {
            pickupTimeId
            pickupDate
            timeText
          }
        }
      `,
      variables: {
        storeId: this.orderInformation.marketplaceStore.id,
        orderNo: this.orderInformation.orderNo,
        addressId: selectedAddressId.toString()
      }
    })

    if (!response.errors) {
      this.timeSlotData = {
        records: response.data.getTimeSlot || []
      }
    }
  }

  _selectPickup() {
    const selectedPickup = this.logisticsPickupGrist.selected[0]
    const selectedTimeSlot = this.timeslotPickupGrist.selected[0]
    if (selectedPickup && selectedTimeSlot) {
      this.dispatchEvent(
        new CustomEvent('selected', {
          detail: {
            addressInfo: selectedPickup,
            timeslot: selectedTimeSlot
          }
        })
      )
      history.back()
    } else {
      document.dispatchEvent(
        new CustomEvent('notify', { detail: { message: i18next.t('text.pickup_info_is_not_completed') } })
      )
    }
  }
}

window.customElements.define('pickup-logistics-popup', PickupLogisticsPopup)
