import '@things-factory/barcode-ui'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin.js'

import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { openOverlay } from '@things-factory/layout-base'
import { client, PageView, store, navigate } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

import { ARRIVAL_NOTICE, RETURN_ORDER } from '../constants'

const AVAIL_ORDER_TYPES = { ARRIVAL_NOTICE, RETURN_ORDER }

class UnloadProductLandingPage extends connect(store)(localize(i18next)(PageView)) {
    static get properties() {
        return {
            refOrderType: String,
            _validating: Boolean
        }
    }

    static get styles() {
        return [
            MultiColumnFormStyles,
            css`
                :host {
                    display: flex;
                    flex-direction: column;
                    overflow: hidden;
                }
                
                .content-wrapper {
                    padding: 0px 16px 0px 16px;
                }
                
                h3 {
                    color: #017E7F;
                    font-weight: bold;
                    font-size: 14px;
                    margin: 15px 0px 0px 0px;
                    padding: 8px 0;
                    border-bottom: 1px solid #017E7F;
                }
                
                /* Override multi-column-form to stack vertically */
                .multi-column-form {
                    display: flex;
                    flex-direction: column;
                    gap: 20px;
                    padding: 0;
                }
                
                .multi-column-form fieldset {
                    display: flex;
                    flex-direction: column;
                    align-items: flex-start !important;
                    border: none;
                    margin: 0;
                    padding: 0;
                    width: 100%;
                    box-sizing: border-box;
                }
                
                .multi-column-form label {
                    display: block;
                    grid-column: unset !important;
                    text-align: left !important;
                    align-self: flex-start !important;
                    margin-bottom: 8px;
                    color: #333;
                    font-weight: bold;
                    font-size: 14px;
                    width: 100%;
                }
                
                .multi-column-form select {
                    grid-column: unset !important;
                    width: 100%;
                    max-width: 100%;
                    min-height: 40px;
                    box-sizing: border-box;
                }
                
                .multi-column-form [custom-input] {
                    grid-column: unset !important;
                    width: 100%;
                    box-sizing: border-box;
                }
                
                .multi-column-form barcode-scanable-input {
                    width: 100%;
                    max-width: 100%;
                    box-sizing: border-box;
                    min-width: 0;
                }
            `
        ]
    }

    get context() {
        return {
            title: i18next.t('title.unloading')
        }
    }

    get orderNoInput() {
        return this.shadowRoot.querySelector('barcode-scanable-input[name=orderNo]')?.shadowRoot?.querySelector('input')
    }

    constructor() {
        super()
        this.refOrderType = AVAIL_ORDER_TYPES.ARRIVAL_NOTICE.value
        this._validating = false
    }

    async pageInitialized() {
        // Only show on mobile
        if (!isMobileDevice()) {
            navigate('unloading')
            return
        }

        await this.updateComplete
        this._focusOnOrderNoField()
    }

    pageUpdated(changes, after, before) {
        if (!isMobileDevice() && this.active) {
            navigate('unloading')
        }
    }

    _focusOnOrderNoField() {
        setTimeout(() => {
            if (this.orderNoInput) {
                this.orderNoInput.focus()
            }
        }, 100)
    }

    orderTypeChangeHandler(e) {
        this.refOrderType = e.currentTarget.value
        if (this.orderNoInput) {
            this.orderNoInput.value = ''
        }
        this._focusOnOrderNoField()
    }

    async _validateAndNavigate() {
        if (this._validating) return

        const orderNo = this.orderNoInput?.value?.trim()
        if (!orderNo) {
            this._showToast({ message: i18next.t('text.please_enter_order_no'), type: 'warning' })
            return
        }

        this._validating = true

        try {
            let orderExists = false

            if (this.refOrderType === AVAIL_ORDER_TYPES.ARRIVAL_NOTICE.value) {
                const response = await client.query({
                    query: gql`
                        query checkUnloadingWorksheet($arrivalNoticeNo: String!) {
                        unloadingWorksheet(arrivalNoticeNo: $arrivalNoticeNo) {
                            worksheetInfo {
                            arrivalNotice {
                                id
                                name
                            }
                            }
                        }
                        }
                    `,
                    variables: { arrivalNoticeNo: orderNo }
                })
                orderExists = !response.errors && response.data?.unloadingWorksheet?.worksheetInfo?.arrivalNotice?.id
            } else if (this.refOrderType === AVAIL_ORDER_TYPES.RETURN_ORDER.value) {
                const response = await client.query({
                    query: gql`
                        query checkUnloadingReturnWorksheet($returnOrderNo: String!) {
                        unloadingReturnWorksheet(returnOrderNo: $returnOrderNo) {
                            worksheetInfo {
                            bizplaceName
                            }
                        }
                        }
                    `,
                    variables: { returnOrderNo: orderNo }
                })
                orderExists = !response.errors && response.data?.unloadingReturnWorksheet?.worksheetInfo
            }

            if (!orderExists) {
                this._validating = false
                return
            }

            // Order exists, navigate to main page with params
            const searchParams = new URLSearchParams()
            searchParams.append('orderType', this.refOrderType)
            searchParams.append('orderNo', orderNo)

            let url = `unloading?${searchParams.toString()}`

            navigate(url)
        } catch (e) {
            this._showToast({ message: e.message || i18next.t('text.error_occurred'), type: 'error' })
        } finally {
            this._validating = false
        }
    }

    _handleOrderNoSubmit(e) {
        if (e.keyCode === 13) {
            e.preventDefault()
            this._validateAndNavigate()
        }
    }

    _showToast({ type, message }) {
        document.dispatchEvent(
            new CustomEvent('notify', {
                detail: {
                    type,
                    message
                }
            })
        )
    }

    render() {
        // IF DESKTOP VIEW, RETURN EMPTY (SAFE GUARD MECHANISM)
        if (!isMobileDevice()) {
            return html``
        }

        return html`
            <div class="content-wrapper">
                <h3>Scan</h3>
                
                <form id="info-form" class="multi-column-form">
                    <fieldset>
                        <label>${i18next.t('label.order_type')}</label>
                        <select name="orderType" @change="${this.orderTypeChangeHandler.bind(this)}" ?disabled="${this._validating}">
                            ${Object.keys(AVAIL_ORDER_TYPES).map(key =>
                                this.refOrderType === AVAIL_ORDER_TYPES[key].value
                                    ? html`
                                        <option value="${AVAIL_ORDER_TYPES[key].value}" selected>
                                        ${i18next.t(`label.${AVAIL_ORDER_TYPES[key].name}`)}
                                        </option>
                                    `
                                    : html`
                                        <option value="${AVAIL_ORDER_TYPES[key].value}">
                                        ${i18next.t(`label.${AVAIL_ORDER_TYPES[key].name}`)}
                                        </option>
                                    `
                            )}
                        </select>
                    </fieldset>

                    <fieldset>
                        <label>${i18next.t('label.order_no')}</label>
                        <barcode-scanable-input
                            name="orderNo"
                            custom-input
                            ?disabled="${this._validating}"
                            @keypress="${this._handleOrderNoSubmit.bind(this)}"
                        ></barcode-scanable-input>
                    </fieldset>
                </form>
            </div>
        `
    }
}

window.customElements.define('unload-product-landing-page', UnloadProductLandingPage)
