import { MultiColumnFormStyles } from '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { EXPORT } from '@things-factory/export-base'
import { store } from '@things-factory/shell'
import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup } from '@things-factory/layout-base'
import { client, PageView } from '@things-factory/shell'
import { connect } from 'pwa-helpers/connect-mixin'
import { CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { ORDER_STATUS, WORKSHEET_STATUS, WORKSHEET_TYPE } from '../constants'
import { fetchSettingRule } from '../../fetch-setting-value'
import './cycle-count-recheck-popup'
import './cycle-count-inventory-details-popup'

class CycleCountReport extends connect(store)(localize(i18next)(PageView)) {
  static get properties() {
    return {
      _worksheetNo: String,
      _reportStatus: String,
      _cycleCountNo: String,
      _orgInventoryAccuracy: Number,
      _enableCartonLabel: Boolean,
      _countData: Array,
      _countUomData: Array,
      _searchFields: Array,
      cycleCountType: String,
      customerId: String,
      inventoryAccuracy: String,
      _firstItem: Object,
      config: Object,
      data: Object
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: auto;
        }
        .form-container {
          display: flex;
        }
        .form-container > form {
          flex: 1;
        }
        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        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);
        }
        .grist h2 {
          margin: var(--grist-title-margin);
          border: var(--grist-title-border);
          font: var(--grist-title-font);
          color: var(--secondary-color);
        }
        .grist h2 mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
        }
        h2 + data-grist {
          padding-top: var(--grist-title-with-grid-padding);
        }
      `
    ]
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.back'),
        action: () => history.back(),
        ...CommonButtonStyles.back
      },
      // export as xlsx
      {
        title: i18next.t('button.inventory_audit_overview'),
        action: this._exportInventoryAuditOverview.bind(this),
        ...CommonButtonStyles.export
      }
    ]

    return {
      title: i18next.t('title.cycle_count_report'),
      actions,
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: this._cycleCountNo,
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/inventory-check/cycle-count-report'
    }
  }

  render() {
    return html`
      <div class="form-container">
        <form class="multi-column-form">
          <fieldset>
            <legend>${i18next.t('title.cycle_count')}</legend>
            <label>${i18next.t('label.company')}</label>
            <input name="company" readonly />
            <label>${i18next.t('label.inventory_check_no')}</label>
            <input name="cycleCountNo" readonly />
            <label>${i18next.t('label.execute_date')}</label>
            <input name="executionDate" readonly />
            <label>${i18next.t('label.inventory_accuracy')}</label>
            <input name="inventoryAccuracy" readonly />
            <label>${i18next.t('label.status')}</label>
            <select name="status" disabled>
              ${Object.keys(ORDER_STATUS).map(
                key => html`
                  <option value="${ORDER_STATUS[key].value}">${i18next.t(`label.${ORDER_STATUS[key].name}`)}</option>
                `
              )}
            </select>
          </fieldset>
        </form>
      </div>
      <search-form id="search-form" .fields=${this._searchFields} @submit=${e => this.dataGrist.fetch()}></search-form>
      <div class="grist">
        <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.inventory')}</h2>
        <data-grist
          id="grist"
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .fetchHandler="${this.fetchCycleCountReport.bind(this)}"
        ></data-grist>
      </div>
    `
  }

  constructor() {
    super()
    this._enableCartonLabel = false
    this._firstItem = {}
    this._orgInventoryAccuracy = null
  }

  async pageUpdated(changes) {
    if (this.active && (changes.resourceId || this._cycleCountNo)) {
      if (changes.resourceId) {
        this._cycleCountNo = changes.resourceId
      }

      await this.fetchCycleCountReport()
      this.config = { ...this.cycleCountConfig }
    }

    this.resetSearchForm()
    this._clearView()
  }

  async pageInitialized() {
    this.isUserBelongsDomain = await this._checkUserBelongsDomain()
    this.config = this.cycleCountConfig

    this._searchFields = [
      {
        name: 'batchNoVariance',
        label: i18next.t('field.batch_no_variance'),
        type: 'checkbox',
        value: false,
        props: { searchOper: 'eq' }
      },
      {
        name: 'expirationDateVariance',
        label: i18next.t('field.expiration_date_variance'),
        type: 'checkbox',
        value: false,
        props: { searchOper: 'eq' }
      },
      {
        name: 'locationVariance',
        label: i18next.t('field.location_variance'),
        type: 'checkbox',
        value: false,
        props: { searchOper: 'eq' }
      }
    ]
  }

  get cycleCountConfig() {
    let data = this._countData || {}
    // Generate UOM Count Columns
    const countColumns = Object.keys(data)
      .filter(key => key.startsWith('count ') && data[key] !== null && data[key] !== undefined)
      .map(key => ({
        type: 'integer',
        name: key,
        header: key,
        width: 120
      }))

    // Generate UOM Value Columns
    const uomValueColumns = Object.keys(data)
      .filter(key => key.startsWith('count ') && data[key] !== null && data[key] !== undefined)
      .map((key, index) => {
        const inspectedValueKey = `uom count ${index + 1}`
        return {
          type: 'integer',
          name: inspectedValueKey,
          header: `UOM Value ${key}`,
          width: 150
        }
      })

    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'gutter',
        gutterName: 'button',
        icon: 'reorder',
        handlers: {
          click: this._showInventoryDetailsPopup.bind(this)
        }
      },
      {
        type: 'string',
        name: 'inventoryId',
        hidden: true
      },
      {
        type: 'string',
        name: 'cartonId',
        header: i18next.t('field.carton_id'),
        width: 120,
        hidden: !this._enableCartonLabel
      },
      {
        type: 'string',
        name: 'palletId',
        header: i18next.t('field.lot_id'),
        width: 120,
        hidden: this._enableCartonLabel
      },
      {
        type: 'string',
        name: 'sku',
        header: i18next.t('field.sku'),
        width: 150
      },
      {
        type: 'string',
        name: 'productName',
        header: i18next.t('field.product'),
        width: 350
      },
      {
        type: 'string',
        name: 'packingType',
        header: i18next.t('field.packing_type'),
        width: 100
      },
      {
        type: 'float',
        name: 'systemQty',
        header: i18next.t('field.system_qty'),
        width: 100
      },
      ...countColumns,
      {
        type: 'string',
        name: 'finalCount',
        header: i18next.t('field.final_count'),
        width: 100
      },
      {
        type: 'string',
        name: 'systemUomValue',
        header: i18next.t('field.system_uom_value'),
        width: 150
      },
      ...uomValueColumns,
      {
        type: 'string',
        name: 'finalUom',
        header: i18next.t('field.final_uom_value'),
        width: 150
      },
      {
        type: 'string',
        name: 'uom',
        header: i18next.t('field.uom'),
        width: 80
      },
      {
        type: 'string',
        name: 'countVariance',
        header: i18next.t('field.count_variance'),
        width: 120
      },
      {
        type: 'boolean',
        name: 'uomValueVariance',
        header: i18next.t('field.uom_value_variance'),
        width: 150,
        renderer: value => {
          return `<input type="checkbox" ${value ? 'checked' : ''} disabled/>`
        },
        hidden: this._enableCartonLabel
      },
      {
        type: 'string',
        name: 'countStatus',
        header: i18next.t('field.count_status'),
        width: 100
      }
    ]

    let list = {
      fields: ['cartonId', 'palletId', 'sku', 'productName', 'packingType']
    }

    return {
      columns: columns,
      list,
      pagination: { infinite: true },
      rows: {
        appendable: false,
        classifier: (record, rowIndex) => {
          return {
            emphasized:
              record.status === WORKSHEET_STATUS.NOT_TALLY.value || record.status === WORKSHEET_STATUS.ADJUSTED.value
          }
        }
      }
    }
  }

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

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

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

  _clearView() {
    this._orgInventoryAccuracy = null
  }

  async fetchCycleCountReport() {
    if (!this._cycleCountNo) return
    let total
    let filters = await this.searchForm.getQueryFilters()
    try {
      const response = await client.query({
        query: gql`
          query cycleCountReport($filters: [Filter], $pagination: Pagination, $sortings: [Sorting], $name: String!) {
            cycleCountReport(filters: $filters, pagination: $pagination, sortings: $sortings, name: $name) {
              items {
                inventoryCheck {
                  name
                  executionDate
                  status
                }
                inventoryCheckItem {
                  originBatchNo
                  inspectedBatchNo
                  originUomValue
                  inspectedUomValue
                  originQty
                  inspectedQty
                  originLocation {
                    name
                  }
                  inspectedLocation {
                    name
                  }
                  status
                }
                inventory {
                  id
                  cartonId
                  palletId
                  packingType
                  uom
                }
                product {
                  sku
                  name
                  brand
                  description
                }
                productDetail {
                  packingType
                  uom
                }
                systemQty
                systemBatchNo
                systemLocationName
                systemUomValue
                originLocationId
                inspectedLocationId
                countData
                countUomData
                batchNoVariance
                locationVariance
                uomValueVariance
                expirationDateVariance
                countVariance
                countStatus
                company
                finalCount
                finalUom
                partnerDomainId
              }
              total
            }
          }
        `,
        variables: {
          filters: filters,
          pagination: null,
          sortings: [],
          name: this._cycleCountNo
        }
      })

      if (!response.errors) {
        const firstItem = response.data.cycleCountReport?.items[0] || this._firstItem
        if (!firstItem) return

        const {
          inventoryCheck: { name: inventoryCheckName, executionDate, status },
          company,
          partnerDomainId
        } = firstItem

        this._firstItem = firstItem
        this._enableCartonLabel = await fetchSettingRule('enable-carton-label', partnerDomainId)
        await this.updateComplete

        let records =
          response.data.cycleCountReport.items.map((item, idx) => {
            const {
              inventory,
              inventoryCheck: { name: inventoryCheckName },
              inventoryCheckItem,
              product: { sku, name: productName, brand, description },
              productDetail: { packingType: pdPackingType, uom: pdUom }
            } = item

            // Parsing countData from string to object & convert to int or replace with "-"
            let countData = JSON.parse(item.countData)
            let countUomData = JSON.parse(item.countUomData)

            const mapCountData = (data, prefix) => {
              return Object.keys(data).reduce((acc, key) => {
                if (key.startsWith(prefix)) {
                  acc[key] = !isNaN(parseFloat(data[key])) && isFinite(data[key]) ? parseFloat(data[key]) : '-'
                }
                return acc
              }, {})
            }

            const findLatestCount = (data, prefix) => {
              return [...Object.keys(data)].filter(key => key.startsWith(prefix) && data[key] !== '-').pop()
            }

            this._countData = mapCountData(countData, 'count')
            this._countUomData = mapCountData(countUomData, 'uom count')

            // Calculate the latest count key and finalCount
            const latestCountKey = findLatestCount(this._countData, 'count ')
            const latestUomCountKey = findLatestCount(this._countUomData, 'uom count ')

            // Calculate finalCount based on the latest count
            const finalCount = latestCountKey ? this._countData[latestCountKey] : item.systemQty
            const finalUom = latestUomCountKey ? this._countUomData[latestUomCountKey] : item.systemUomValue

            // Calculate countVariance
            let countVariance = finalCount - item.systemQty

            // Calculate countStatus
            let countStatus
            const {
              status,
              inspectedBatchNo,
              inspectedQty,
              inspectedUomValue,
              originBatchNo,
              originQty,
              originUomValue,
              originLocation,
              inspectedLocation
            } = inventoryCheckItem
            const originLocationName = originLocation.name
            const inspectedLocationName = inspectedLocation.name
            const { id: inventoryId, cartonId, palletId, packingType: invPackingType, uom: invUom } = inventory

            let batchNoVariance = item.batchNoVariance
            let expirationDateVariance = item.expirationDateVariance
            let locationVariance = item.locationVariance
            let uomValueVariance = item.uomValueVariance

            if (
              inventoryCheckItem.status === ORDER_STATUS.INSPECTING.value ||
              inventoryCheckItem.status === ORDER_STATUS.PENDING.value
            ) {
              // reset variance value if cc is not executed yet
              countStatus = 'PENDING'
              countVariance = 0
              batchNoVariance = null
              expirationDateVariance = null
              locationVariance = null
              uomValueVariance = null
            } else if (finalCount === item.systemQty) {
              countStatus = 'HIT'
            } else if (finalCount < item.systemQty) {
              countStatus = 'SHORT'
            } else if (finalCount > item.systemQty) {
              countStatus = 'EXCESS'
            }

            return {
              ...this._countData,
              ...this._countUomData,
              inventoryId,
              cartonId,
              palletId,
              name: inventoryCheckName,
              executionDate,
              originBatchNo,
              inspectedBatchNo,
              originUomValue: parseFloat(originUomValue) || 0,
              inspectedUomValue: parseFloat(inspectedUomValue) || 0,
              originQty: parseFloat(originQty) || 0,
              inspectedQty: parseFloat(inspectedQty) || 0,
              systemQty: parseFloat(item.systemQty) || 0,
              systemBatchNo: item.systemBatchNo,
              systemLocationName: item.systemLocationName,
              systemUomValue: parseFloat(item.systemUomValue) || 0,
              finalUom: item.finalUom,
              originLocationId: item.originLocationId,
              originLocationName,
              inspectedLocationId: item.inspectedLocationId,
              inspectedLocationName,
              sku,
              productName,
              brand,
              description,
              packingType: invPackingType || pdPackingType,
              uom: invUom || pdUom,
              runningNo: idx + 1,
              batchNoVariance: batchNoVariance,
              locationVariance: locationVariance,
              uomValueVariance: uomValueVariance,
              expirationDateVariance: expirationDateVariance,
              countVariance: Number(Number(item.countVariance).toFixed(3)),
              countStatus,
              company: item.company,
              finalCount,
              finalUom
            }
          }) || []

        const totalSKUWithHIT = records.filter(record => record.countStatus === 'HIT').length
        const totalSKUInCycleCount = records.length
        const inventoryAccuracy = (totalSKUWithHIT / totalSKUInCycleCount) * 100

        if (!this._orgInventoryAccuracy) {
          this._orgInventoryAccuracy = inventoryAccuracy
        }

        this._fillupForm({
          company,
          cycleCountNo: inventoryCheckName,
          executionDate,
          status,
          inventoryAccuracy: this._orgInventoryAccuracy.toFixed(2) + '%'
        })

        total = records.length

        if (this._enableCartonLabel) {
          const groupedRecords = {}
          records.forEach(record => {
            const groupKey = `${record.cartonId || ''}-${record.sku || ''}-${record.originBatchNo || ''}-${
              record.originLocationId || ''
            }`
            if (!groupedRecords[groupKey]) {
              groupedRecords[groupKey] = { ...record, count: 1, systemQty: record.systemQty }
            } else {
              groupedRecords[groupKey].systemQty += record.systemQty
              Object.keys(record).forEach(key => {
                if (key.startsWith('count ') && record[key] !== '-') {
                  groupedRecords[groupKey][key] = (groupedRecords[groupKey][key] || 0) + (parseFloat(record[key]) || 0)
                }
              })
              groupedRecords[groupKey].count += 1
            }
          })

          records = Object.values(groupedRecords).map(groupedRecord => {
            const latestCountKey = [...Object.keys(groupedRecord)]
              .filter(key => key.startsWith('count ') && groupedRecord[key] !== '-')
              .pop()

            const finalCount = latestCountKey ? groupedRecord[latestCountKey] : groupedRecord['systemQty']
            let countVariance = Number((finalCount - groupedRecord['systemQty']).toFixed(3))

            let countStatus
            if (groupedRecord.countStatus === ORDER_STATUS.PENDING.value) {
              countStatus = groupedRecord.countStatus
              countVariance = Number(groupedRecord.countVariance.toFixed(3))
            } else if (finalCount === groupedRecord.systemQty) {
              countStatus = 'HIT'
            } else if (finalCount < groupedRecord.systemQty) {
              countStatus = 'SHORT'
            } else if (finalCount > groupedRecord.systemQty) {
              countStatus = 'EXCESS'
            }

            return {
              ...groupedRecord,
              finalCount,
              countVariance,
              countStatus
            }
          })
          total = Object.keys(groupedRecords).length
        }
        this._updateColumnVisibility()
        this.updateContext()
        return { records, total }
      } else {
        console.error(response.errors)
      }
    } catch (error) {
      console.error(error)
    }
  }

  _updateColumnVisibility() {
    if (this.config && this.config.columns) {
      const uomValueVarianceColumn = this.config.columns.find(col => col.name === 'uomValueVariance')
      const cartonIdColumn = this.config.columns.find(col => col.name === 'cartonId')
      const palletIdColumn = this.config.columns.find(col => col.name === 'palletId')

      if (cartonIdColumn) {
        cartonIdColumn.hidden = !this._enableCartonLabel
      }
      if (palletIdColumn && uomValueVarianceColumn) {
        palletIdColumn.hidden = this._enableCartonLabel
        uomValueVarianceColumn.hidden = this._enableCartonLabel
      }
    }
  }

  _fillupForm(data) {
    for (let key in data) {
      Array.from(this.form.querySelectorAll('input, select')).forEach(field => {
        if (field.name === key && field.type === 'checkbox') {
          field.checked = data[key]
        } else if (field.name === key) {
          if (data[key] instanceof Object) {
            const objectData = data[key]
            field.value = `${objectData.name} ${objectData.description ? `(${objectData.description})` : ''}`
          } else {
            field.value = data[key]
          }
        }
      })
    }
  }

  _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
    }
  }

  _showInventoryDetailsPopup(columns, data, column, record, rowIndex) {
    if (record.inventoryId && this._cycleCountNo) {
      const title = record.cartonId ? `[${record.cartonId}] ${record.sku}` : `[${record.palletId}] ${record.sku}`

      openPopup(
        html`
          <cycle-count-inventory-details-popup
            .inventoryId="${record.inventoryId}"
            .cartonId="${record.cartonId}"
            .pallet="${record.palletId}"
            .cycleCountNo="${this._cycleCountNo}"
            .enableCartonLabel="${this._enableCartonLabel}"
          ></cycle-count-inventory-details-popup>
        `,
        {
          backdrop: true,
          size: 'large',
          title: title
        }
      )
    }
  }

  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 _exportableData() {
    try {
      let data = []

      var headerSetting = [
        { header: i18next.t('field.carton_id'), key: 'cartonId', width: 25, type: 'string' },
        { header: i18next.t('field.lot_id'), key: 'palletId', width: 25, type: 'string' },
        { header: i18next.t('field.sku'), key: 'sku', width: 25, type: 'string' },
        { header: i18next.t('field.product'), key: 'productName', width: 60, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'description', width: 60, type: 'string' },
        { header: i18next.t('field.packing_type'), key: 'packingType', width: 20, type: 'string' },
        { header: i18next.t('field.system_batch_no'), key: 'systemBatchNo', width: 25, type: 'string' },
        { header: i18next.t('field.inspected_batch_no'), key: 'inspectedBatchNo', width: 25, type: 'string' },
        { header: i18next.t('field.system_location'), key: 'systemLocationName', width: 25, type: 'string' },
        { header: i18next.t('field.inspected_location'), key: 'inspectedLocationName', width: 25, type: 'string' },
        { header: i18next.t('field.system_qty'), key: 'systemQty', width: 20, type: 'string' },
        { header: i18next.t('field.final_count'), key: 'finalCount', width: 20, type: 'string' },
        { header: i18next.t('field.system_uom_value'), key: 'systemUomValue', width: 25, type: 'string' },
        { header: i18next.t('field.final_uom_value'), key: 'finalUom', width: 25, type: 'string' },
        { header: i18next.t('field.uom'), key: 'uom', width: 25, type: 'string' },
        { header: i18next.t('field.count_variance'), key: 'countVariance', width: 20, type: 'string' },
        { header: i18next.t('field.uom_value_variance'), key: 'uomValueVariance', width: 20, type: 'string' },
        { header: i18next.t('field.count_status'), key: 'countStatus', width: 20, type: 'string' }
      ]

      data = (await this.fetchCycleCountReport({ page: 1, limit: 999999 })).records

      const indexToInsert = headerSetting.findIndex(header => header.key === 'systemQty')
      if (indexToInsert === -1) {
        console.error('systemQty header not found in headerSetting')
        return
      }

      if (data.length > 0) {
        const dynamicColumns = Object.keys(data[0]).filter(key => key.startsWith('count '))
        const dynamicHeaders = dynamicColumns.map(column => {
          return {
            header: column,
            key: column,
            width: 20,
            type: 'string'
          }
        })

        headerSetting.splice(indexToInsert + 1, 0, ...dynamicHeaders)
      }

      const indexToInsertUOM = headerSetting.findIndex(header => header.key === 'finalUom')
      if (indexToInsertUOM === -1) {
        console.error('finalUom header not found in headerSetting')
        return
      }

      const uomValueColumns = Object.keys(data[0] || {}).filter(
        key => key.startsWith('count ') && data[0][key] !== null && data[0][key] !== undefined
      )

      const uomHeaders = uomValueColumns.map((column, index) => {
        const inspectedValueKey = `uom count ${index + 1}`
        return {
          header: `UOM Value Count ${index + 1}`,
          key: inspectedValueKey,
          width: 25,
          type: 'string'
        }
      })

      headerSetting.splice(indexToInsertUOM, 0, ...uomHeaders)

      return { header: headerSetting, data }
    } catch (e) {
      this._showToast(e)
    }
  }
  async _exportInventoryAuditOverview() {
    try {
      let data = []

      var headerSetting = [
        { header: i18next.t('field.sku'), key: 'sku', width: 20, type: 'string' },
        { header: i18next.t('field.system_qty'), key: 'systemQty', width: 20, type: 'string' },
        { header: i18next.t('field.final_count'), key: 'finalCount', width: 20, type: 'string' },
        { header: i18next.t('field.variance'), key: 'countVariance', width: 20, type: 'string' },
        { header: i18next.t('field.status'), key: 'countStatus', width: 20, type: 'string' }
      ]

      data = (await this.fetchCycleCountReport({ page: 1, limit: 999999 })).records

      store.dispatch({
        type: EXPORT,
        exportable: {
          extension: 'xlsx',
          name: this._cycleCountNo,
          data: { header: headerSetting, data }
        }
      })
    } catch (e) {
      this._showToast(e)
    }
  }

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

  //to reset search-form values when exit page
  resetSearchForm() {
    const searchForm = this.shadowRoot.querySelector('#search-form')
    if (searchForm) {
      searchForm.formFields.forEach(field => {
        if (field.type === 'checkbox') {
          field.checked = false
          field.removeAttribute('indeterminate')
          field._value = undefined
        } else {
          field.value = ''
        }
      })
    }
  }
}

window.customElements.define('cycle-count-report', CycleCountReport)
