import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import '@things-factory/worksheet-ui'
import '../batch-picking-popup'
import '../packing-label-history-popup'
import '../../../outbound/generate-worksheet-popup'
import '../../../outbound/select-operator-popup'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'

import { getCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup, openOverlay } from '@things-factory/layout-base'
import { client, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice, sleep } from '@things-factory/utils'

import { ORDER_STATUS, ORDER_VAS_STATUS, RTM_OPTIONS } from '../../../constants'
import { fetchSettingRule } from '../../../../fetch-setting-value'

import { applyParamsToFields } from '../../../../util'

class B2bOrderList extends localize(i18next)(PageView) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }

        data-grist {
          overflow-y: auto;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      config: Object,
      data: Object,
      _ownTransport: Boolean,
      _exportOption: Boolean,
      _routeId: Boolean,
      vasStatus: String,
      isUserBelongsDomain: Boolean,
      _enableZonePicking: Boolean,
      _betaSetting: Boolean
    }
  }

  constructor() {
    super()
    this._hasSelectionListener = false
  }

  render() {
    return html`
      <search-form id="search-form" .fields=${this._searchFields} @submit=${e => this.dataGrist.fetch()}></search-form>

      <data-grist
        .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
        .config=${this.config}
        .fetchHandler="${this.fetchHandler.bind(this)}"
      ></data-grist>
    `
  }

  get context() {
    var actions = []

    actions.push({
      title: i18next.t('title.packing_label_history'),
      action: this._openPackingLabelHistory.bind(this),
      icon: 'history',
      emphasis: {
        raised: false,
        outlined: true,
        dense: false,
        danger: false
      }
    })

    if (this._shouldShowButtonForSelection()) {
      actions.push({
        title: i18next.t('title.print_packing_label'),
        action: this._openPrintPackingList.bind(this),
        icon: 'print',
        emphasis: {
          raised: false,
          outlined: true,
          dense: false,
          danger: false
        }
      })
    }

    if (this.isUserBelongsDomain) {
      if (this._betaSetting) {
        actions.push({
          title: i18next.t('button.generate_worksheet'),
          action: this._openWorksheetOverlay.bind(this),
          ...CommonButtonStyles.activate
        })
      } else {
        actions.push({
          title: i18next.t('button.generate_worksheet'),
          action: this._openGenerateWorksheetPopup.bind(this),
          ...CommonButtonStyles.activate
        })
      }
    }

    if (this._enableZonePicking) {
      actions.push({
        title: i18next.t('button.assign_sorter'),
        action: this._openSelectSorterPopup.bind(this),
        ...CommonButtonStyles.add
      })
    }

    return {
      title: i18next.t('title.release_orders'),
      actions,
      exportable: {
        name: i18next.t('title.release_orders'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/release-order/ro-list'
    }
  }

  get _fromDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=fromDate]')
  }

  get _toDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=toDate]')
  }

  pageUpdated(changes, lifecycle) {
    if (this.active) {
      let { params } = lifecycle
      if (params && this._searchFields) {
        if (params.range) {
          params.toDate = new Date().toISOString().split('T')[0]
          switch (params.range) {
            case '1d':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0]
              break
            case '1w':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().split('T')[0]
              break
            case '1m':
              params.fromDate = new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().split('T')[0]
              break
            default:
              break
          }
        }
        const updatedFields = applyParamsToFields(this._searchFields, params)
        this._searchFields = updatedFields
        const searchForm = this.searchForm
        if (searchForm) {
          searchForm.fields = updatedFields
        }
      }

      this.dataGrist.fetch()
    }
  }

  async pageInitialized() {
    this.isUserBelongsDomain = await this._checkUserBelongsDomain()
    const [_orderStatusReq, _bizplacesReq] = await Promise.allSettled([
      getCodeByName('RO_REQUESTS_STATUS'),
      this._fetchBizplaces()
    ])

    const _orderStatus = _orderStatusReq.status == 'fulfilled' ? _orderStatusReq.value : []
    const _bizplaces = _bizplacesReq.status == 'fulfilled' ? _bizplacesReq.value : []
    const _excludedVasStatus = ['DONE', 'CHANGES', 'NEW', 'REMOVED']
    const _orderVasStatus = Object.values(ORDER_VAS_STATUS).filter(status => !_excludedVasStatus.includes(status.value))
    this._enableZonePicking = await fetchSettingRule('enable-zone-picking')
    this._betaSetting = await fetchSettingRule('enable-beta-feature')

    this._searchFields = [
      {
        label: i18next.t('field.order_info'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ..._bizplaces
            .map(bizplace => {
              return {
                name: `${bizplace.name} ${bizplace.description ? `(${bizplace.description})` : ''}`,
                value: bizplace.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      // {
      //   label: i18next.t('field.release_date'),
      //   name: 'releaseDate',
      //   type: 'date',
      //   props: { searchOper: 'i_like' }
      // },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ..._orderStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.vas_status'),
        name: 'vasStatus',
        type: 'select',
        options: [
          { value: '' },
          ..._orderVasStatus.map(status => {
            return { name: i18next.t(`label.${status.name}`), value: status.value }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'sku',
        type: 'text',
        props: { searchOper: ' i_like' }
      },
      {
        label: i18next.t('field.from'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'gte'
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 6)
          return date.toISOString().split('T')[0]
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'lte',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 6)
            return date.toISOString().split('T')[0]
          })()
        },
        value: new Date().toISOString().split('T')[0]
      },
      {
        label: i18next.t('field.rtm'),
        name: 'rtm',
        type: 'select',
        props: { searchOper: 'eq' },
        options: [{ value: '' }, ...RTM_OPTIONS.map(option => ({ name: option.label, value: option.value }))]
      },
      {
        label: i18next.t('field.based_on_release_date'),
        name: 'isReleaseDateSearch',
        type: 'checkbox',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.export_option'),
        name: 'exportOption',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.own_transport'),
        name: 'ownTransport',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.route_label'),
        name: 'routeId',
        type: 'checkbox',
        props: { searchOper: 'noteq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.recall'),
        name: 'recall',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.vas'),
        name: 'hasVas',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true }, appendable: false },
      list: { fields: ['name', 'releaseDate', 'status', 'updatedAt'] },
      pagination: { limit: 100, pages: [20, 50, 100, 200, 500] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              const status = record.status
              if (status === ORDER_STATUS.REJECTED.value) {
                navigate(`rejected_release_order/${record.name}`) // 1. move to rejected detail page
              } else {
                navigate(`release_order_detail/${record.name}`)
              }
            }
          }
        },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'assignment_return',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              const { status, name } = record
              if (status === ORDER_STATUS.DONE.value) {
                navigate(`create_return_order?releaseOrderNo=${name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.ro'),
          imex: { header: i18next.t('field.ro'), key: 'name', width: 30, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace.name', width: 30, type: 'string' },
          sortable: true,
          width: 250
        },
        {
          type: 'object',
          name: 'draftReleaseGood',
          header: i18next.t('field.draft_order_no'),
          imex: { header: i18next.t('field.draft_order_no'), key: 'draftReleaseGood.name', width: 30, type: 'string' },
          sortable: true,
          width: 250
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 20, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          imex: { header: i18next.t('field.ref_no_2'), key: 'refNo2', width: 20, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo3',
          header: i18next.t('field.ref_no_3'),
          imex: { header: i18next.t('field.ref_no_3'), key: 'refNo3', width: 20, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'date',
          name: 'releaseDate',
          header: i18next.t('field.release_date'),
          imex: { header: i18next.t('field.release_date'), key: 'releaseDate', width: 20, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'string',
          name: 'rtm',
          header: i18next.t('field.rtm'),
          imex: { header: i18next.t('field.rtm'), key: 'rtm', width: 40, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'exportOption',
          header: i18next.t('field.export_option'),
          imex: { header: i18next.t('field.export_option'), key: 'exportOption', width: 20, type: 'string' },
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'ownTransport',
          header: i18next.t('field.own_transport'),
          imex: { header: i18next.t('field.own_transport'), key: 'ownTransport', width: 20, type: 'string' },
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'crossDocking',
          header: i18next.t('field.cross_docking'),
          imex: { header: i18next.t('field.cross_docking'), key: 'crossDocking', width: 20, type: 'string' },
          width: 60
        },
        {
          type: 'boolean',
          name: 'routeId',
          header: i18next.t('field.route'),
          imex: { header: i18next.t('field.route'), key: 'routeId', width: 20, type: 'string' },
          width: 60
        },
        {
          type: 'boolean',
          name: 'recall',
          header: i18next.t('field.recall'),
          imex: { header: i18next.t('field.recall'), key: 'recall', width: 20, type: 'string' },
          width: 60
        },
        {
          type: 'object',
          name: 'arrivalNotice',
          header: i18next.t('field.gan'),
          imex: { header: i18next.t('field.gan'), key: 'arrivalNotice.name', width: 30, type: 'string' },
          width: 160
        },
        {
          type: 'string',
          name: 'vasStatus',
          header: i18next.t('field.vas_status'),
          imex: { header: i18next.t('field.vas'), key: 'vas', width: 20, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 30, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'object',
          name: 'sortedBy',
          header: i18next.t('field.sorter'),
          imex: { header: i18next.t('field.sorter'), key: 'sortedBy', width: 30, type: 'object' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          imex: { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'datetime' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'acceptedAt',
          header: i18next.t('field.accepted_at'),
          imex: { header: i18next.t('field.accepted_at'), key: 'acceptedAt', width: 30, type: 'datetime' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          imex: { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 30, type: 'datetime' },
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'creator',
          header: i18next.t('field.created_by'),
          imex: { header: i18next.t('field.created_by'), key: 'creator.name', width: 30, type: 'string' },
          sortable: true,
          width: 200
        },
        {
          type: 'object',
          name: 'acceptedBy',
          header: i18next.t('field.accepted_by'),
          imex: { header: i18next.t('field.accepted_by'), key: 'acceptedBy.name', width: 30, type: 'string' },
          sortable: true,
          width: 200
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updated_by'),
          imex: { header: i18next.t('field.updated_by'), key: 'updater.name', width: 30, type: 'string' },
          sortable: true,
          width: 200
        }
      ]
    }

    await this.updateComplete
    if (this.dataGrist && !this._hasSelectionListener) {
      this.dataGrist.addEventListener('select-record-change', () => this.updateContext())
      this.dataGrist.addEventListener('select-all-change', () => this.updateContext())
      this._hasSelectionListener = true
    }
  }

  get searchForm() {
    return this.shadowRoot.querySelector('search-form')
  }

  get dataGrist() {
    return this.shadowRoot.querySelector('data-grist')
  }

  get _columns() {
    return this.config.columns
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    let filters = this.searchForm.queryFilters.map(filter => {
      switch (filter.name) {
        case 'fromDate':
          let fromDt = new Date(filter.value)
          fromDt.setHours(0)
          filter.value = fromDt.toISOString()
          break
        case 'toDate':
          let toDt = new Date(filter.value)
          toDt.setHours(23, 59, 59)
          filter.value = toDt.toISOString()
          break
        default:
          break
      }
      return filter
    })
    const response = await client.query({
      query: gql`
        query releaseGoodRequests($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          releaseGoodRequests(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              bizplace {
                id
                name
                description
              }
              draftReleaseGood {
                id
                name
              }
              ownTransport
              crossDocking
              arrivalNotice {
                id
                name
                description
              }
              refNo
              refNo2
              refNo3
              exportOption
              routeId
              rtm
              releaseDate
              recall
              status
              createdAt
              orderVass {
                id
                status
              }
              sortedBy {
                name
              }
              creator {
                id
                name
                description
              }
              acceptedAt
              acceptedBy {
                id
                name
                description
              }
              updatedAt
              updater {
                id
                name
              }
              activeWorksheet {
                type
                status
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: [...filters, { name: 'type', operator: 'eq', value: 'b2b' }],
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      this._ownTransport = response.data.releaseGoodRequests.ownTransport
      this._exportOption = response.data.releaseGoodRequests.exportOption
      this._routeId = response.data.releaseGoodRequests.routeId ? true : false
      return {
        total: response.data.releaseGoodRequests.total || 0,
        records:
          response.data.releaseGoodRequests.items.map(itm => {
            return {
              ...itm,
              routeId: itm.routeId ? true : false,
              vasStatus:
                itm.orderVass?.length > 0
                  ? itm.orderVass.some(ov => ov.status === ORDER_VAS_STATUS.PENDING_APPROVE.value)
                    ? ORDER_VAS_STATUS.PENDING_APPROVE.value
                    : itm.orderVass[0].status
                  : null
            }
          }) || []
      }
    }
  }

  async _fetchBizplaces() {
    const filters = []
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!]) {
          partnersBizplaces(filters: $filters) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: { filters }
    })

    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }

  async _checkUserBelongsDomain() {
    try {
      const response = await client.query({
        query: gql`
          query {
            checkUserBelongsDomain
          }
        `
      })

      if (!response.errors) {
        return response.data.checkUserBelongsDomain
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _openGenerateWorksheetPopup() {
    try {
      if (this.dataGrist.selected.length <= 0)
        throw new Error(i18next.t('text.please_select_one_or_more_order_to_generate_worksheet'))

      let releaseGoodNos = []

      let readyToPick = this.dataGrist.selected.filter(itm => itm.status === ORDER_STATUS.PENDING_WORKSHEET.value)
      releaseGoodNos = readyToPick.map(record => record.name)

      if (releaseGoodNos.length <= 0)
        throw new Error(i18next.t('text.selected_release_order(s)_is_not_in_pending_worksheet_status'))

      await sleep(1010)
      openPopup(html` <generate-worksheet-popup .gristData=${this.dataGrist}></generate-worksheet-popup> `, {
        backdrop: true,
        size: 'medium',
        title: i18next.t('title.generate_picking_worksheet')
      })
    } catch (e) {
      this._showToast(e)
    }
  }

  _openSelectSorterPopup() {
    try {
      let selectedData = this.dataGrist.selected.filter(
        item => item.status != ORDER_STATUS.DONE.value && item.status != ORDER_STATUS.CANCELLED.value
      )

      if (selectedData.length <= 0) throw new Error('Please select at least one valid order')

      openPopup(
        html`
          <select-operator-popup
            .selectSorter="${true}"
            @updateOperator="${async e => {
              let assignee = e.detail

              const response = await client.mutate({
                mutation: gql`
                  mutation assignSorter($releaseGoodId: [String]!, $userId: String!) {
                    assignSorter(releaseGoodId: $releaseGoodId, userId: $userId)
                  }
                `,
                variables: { releaseGoodId: selectedData.map(itm => itm.id), userId: assignee.id }
              })

              if (!response.errors) {
                this.dataGrist.fetch()
                return this._showToast({ message: i18next.t('text.updated_successfully') })
              }

              if (this.activatable) {
                if (this.orderNo) {
                  history.back()
                }
              }
            }}"
          ></select-operator-popup>
        `,
        {
          backdrop: true,
          size: 'medium',
          title: 'select operator'
        }
      )
    } catch (error) {
      return this._showToast(error)
    }
  }

  _openWorksheetOverlay() {
    // Load smart-batch-picking setting and expose globally for overlay to pass to popup
    fetchSettingRule('smart-batch-picking').then(val => {
      window.__SMART_BATCH_PICKING__ = String(val).toLowerCase() === 'true'
      window.__WORKSHEET_TYPE__ = 'b2b'
      openOverlay('context-toolbar-overlay', {
        template: html` <worksheet-overlay-template></worksheet-overlay-template> `
      })
    })
  }

  _compareValues(key, order = 'asc') {
    return function innerSort(a, b) {
      if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
        return 0
      }

      const varA = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key]
      const varB = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key]

      let comparison = 0
      if (varA > varB) {
        comparison = 1
      } else if (varA < varB) {
        comparison = -1
      }
      return order === 'desc' ? comparison * -1 : comparison
    }
  }

  _modifyDateRange(e) {
    const fromDate = e.currentTarget.value

    if (this._toDateInput.value < fromDate) this._toDateInput.value = fromDate

    let min = new Date(fromDate)
    let today = new Date()
    today.setHours(0, 0, 0, 0)

    min = min.toISOString().split('T')[0]

    this._toDateInput.min = min
  }

  _exportableData() {
    let records = []
    if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
      records = this.dataGrist.selected
    } else {
      records = this.dataGrist.data.records
    }

    var headerSetting = this.dataGrist._config.columns
      .filter(column => column.type !== 'gutter' /* && column.record !== undefined */ && column.imex !== undefined)
      .map(column => {
        return column.imex
      })

    var data = records.map(item => {
      return {
        id: item.id,
        ...this._columns
          .filter(column => column.type !== 'gutter' /* && column.record !== undefined */ && column.imex !== undefined)
          .reduce((record, column) => {
            record[column.imex.key] = column.imex.key
              .split('.')
              .reduce((obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined), item)
            if (column.type === 'datetime') {
              record[column.imex.key] = new Date(parseInt(record[column.imex.key])).toLocaleString()
            }
            return record
          }, {})
      }
    })
    return { header: headerSetting, data: data }
  }

  _shouldShowButtonForSelection() {
    if (!this.dataGrist) return false

    const selected = this.dataGrist.selected || []
    if (selected.length === 0) return false

    const allowedWorksheetTypes = ['LOADING', 'PROCESSING', 'PARTIAL_PROCESSING']
    const allowedWorksheetStatuses = ['EXECUTING', 'PARTIAL_EXECUTING']
    
    return selected.every(order => {
      // Check if activeWorksheet exists
      if (!order.activeWorksheet) return false
      
      // Check if activeWorksheet.type is one of the allowed types
      if (!allowedWorksheetTypes.includes(order.activeWorksheet.type)) return false
      
      // Check if activeWorksheet.status is EXECUTING or PARTIAL_EXECUTING
      return allowedWorksheetStatuses.includes(order.activeWorksheet.status)
    })
  }

  _openPrintPackingList() {
    try {
      if (!this.dataGrist || !this.dataGrist.selected || this.dataGrist.selected.length === 0) {
        throw new Error(i18next.t('text.please_select_one_or_more_order') || 'Please select one or more orders')
      }

      const selectedOrderNames = this.dataGrist.selected.map(order => order.name).filter(Boolean)
      if (selectedOrderNames.length === 0) {
        throw new Error(i18next.t('text.no_valid_orders_selected') || 'No valid orders selected')
      }

      const orderNoParam = selectedOrderNames.join(',')
      navigate(`preview_print_packing_list?orderNo=${encodeURIComponent(orderNoParam)}`)
    } catch (e) {
      this._showToast({ type: 'error', message: e.message || i18next.t('text.failed_to_open_print_packing_label') })
    }
  }

  _openPackingLabelHistory() {
    try {
      openPopup(
        html` <packing-label-history-popup></packing-label-history-popup> `,
        {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.packing_label_history'),
          escapable: false
        }
      )
    } catch (e) {
      this._showToast({ type: 'error', message: e.message || i18next.t('text.failed_to_open_packing_label_history') })
    }
  }

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

window.customElements.define('b2b-order-list', B2bOrderList)
