import '@things-factory/form-ui'
import '@things-factory/grist-ui'

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

import { getCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, gqlContext, PageView, store } from '@things-factory/shell'
import { flattenObject, isMobileDevice } from '@things-factory/utils'
import { LOCATION_TYPE } from '../constants/location'

function formatLocalDate(date = new Date()) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

class BillingModuleReport extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: column;
        width: 100%;
      }

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

  static get properties() {
    return {
      _searchFields: Object,
      _config: Object,
      _partners: Object,
      _gristData: Object,
      data: Object
    }
  }

  get context() {
    return {
      title: i18next.t('title.billing_module'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.billing_module'),
        data: this._exportableData.bind(this)
      }
    }
  }

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

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

  get _bizplaceSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=bizplace]')
  }

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

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

  get _locationTypeSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=locationType]')
  }

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

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

  get searchFields() {
    return [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...this._partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: formatLocalDate(new Date())
        },
        value: (() => {
          const date = new Date()
          date.setMonth(date.getMonth() - 1)
          return formatLocalDate(date)
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            const date = new Date()
            date.setMonth(date.getMonth() - 1)
            return formatLocalDate(date)
          })(),
          max: formatLocalDate(new Date())
        },
        value: formatLocalDate(new Date())
      },
      {
        label: i18next.t('field.location_type'),
        name: 'locationType',
        type: 'select',
        options: [{ value: '' }, ...Object.values(LOCATION_TYPE)],
        props: { searchOper: 'eq' }
      }
    ]
  }

  get reportConfig() {
    this._gristData.records.forEach((record, i) => {
      console.log(`Record ${i}:`, Object.keys(record))
    })

    const dataKeys = this._gristData.records.reduce((keys, item) => {
      Object.keys(item).forEach(key => keys.add(key))
      return keys
    }, new Set())

    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'string',
        name: 'formattedDate',
        imex: { header: i18next.t('field.date'), key: 'formattedDate', width: 15, type: 'date' },
        header: i18next.t('field.date'),
        width: 100
      }
    ]

    const excludedKeys = new Set(['formattedDate']) // Exclude predefined keys
    dataKeys.forEach(key => {
      if (!excludedKeys.has(key)) {
        columns.push({
          type: 'string',
          name: key,
          header: key,
          width: 170,
          imex: { key }
        })
      }
    })

    const filteredColumns = columns
      .filter(column => column.imex && dataKeys.has(column.imex.key))
      .sort((a, b) => {
        const aStartsWithTotal = a.header.toLowerCase().startsWith('total')
        const bStartsWithTotal = b.header.toLowerCase().startsWith('total')

        if (aStartsWithTotal && !bStartsWithTotal) return 1 // Move 'Total' headers down
        if (!aStartsWithTotal && bStartsWithTotal) return -1 // Keep non-'Total' headers first
        return 0
      })

    return {
      columns: filteredColumns,
      pagination: { pages: [20, 50, 100, 200, 500, 1000] },
      rows: {
        selectable: false,
        groups: [{ column: 'formattedDate' }]
      }
    }
  }

  async pageInitialized() {
    this._gristData = { total: 0, totalWithOpeningBalance: 0, records: [] }
    this._products = []
    this._partners = [...(await this._fetchPartners())]

    this._searchFields = this.searchFields
    this._config = this.reportConfig
  }

  async pageUpdated(changes) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()

      let filters = this.searchForm.queryFilters.map(filter => {
        switch (filter.name) {
          case 'fromDate':
            let fromDt = new Date(filter.value)
            filter.value = fromDt.toISOString()
            break
          case 'toDate':
            let toDt = new Date(filter.value)
            toDt.setDate(toDt.getDate() + 1)
            toDt.setSeconds(toDt.getSeconds() - 1)
            filter.value = toDt.toISOString()
            break
          default:
            break
        }

        return filter
      })

      const pagination = { page, limit }
      const sortings = sorters

      const response = await client.query({
        query: gql`
          query billingModuleReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            billingModuleReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                date
                packingType
                quantity
              }
            }
          }
        `,
        variables: { filters, pagination, sortings },
        context: gqlContext()
      })

      // Format dates in the response data after the query
      const formatDate = date => {
        // Check if the input is a number (timestamp in milliseconds)
        const strToNum = Number(date) // Converts string to number

        const isTimestamp = typeof strToNum === 'number'

        const d = isTimestamp ? new Date(strToNum) : new Date(strToNum)

        // Format the date to DD/MM/YYYY
        return d.toLocaleDateString('en-GB') // Example: 26/12/2024
      }

      const formattedRecords = response.data.billingModuleReport.items.reduce((acc, itm) => {
        const formattedDate = itm.date ? formatDate(itm.date) : null

        // Find if the date already exists in the accumulator
        const existingRecord = acc.find(record => record.formattedDate === formattedDate)

        const propertyName = itm.packingType

        if (existingRecord) {
          existingRecord[propertyName] = itm.quantity
        } else {
          const propertyName = itm.packingType

          acc.push({
            formattedDate,
            [propertyName]: itm.quantity ? itm.quantity : '-'
          })
        }

        return acc
      }, [])

      const data = {
        total: formattedRecords.length,
        records: formattedRecords.slice((page - 1) * limit, limit * page) || []
      }

      this._gristData = {
        ...data
      }

      return data
    } catch (e) {
      this._showToast(e)
    }
  }

  async _fetchPartners() {
    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
    }
  }
  _validate() {
    if (!this.searchForm.shadowRoot.querySelector('form').checkValidity())
      throw new Error(i18next.t('text.invalid_form_value'))
    if (!this._bizplaceSelector.value) throw new Error(i18next.t('text.no_company_selected'))
    if (!this._fromDateInput.value) throw new Error(i18next.t('text.from_date_is_empty'))
    if (!this._toDateInput.value) throw new Error(i18next.t('text.to_date_is_empty'))
  }

  _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

    const minDate = new Date(fromDate)
    if (Number.isNaN(minDate.getTime())) return

    const min = formatLocalDate(minDate)
    this._toDateInput.min = min
  }

  async _exportableData() {
    try {
      let data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records

      let header = this.dataGrist._config.columns
        .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
        .map(column => {
          return {
            header: column.imex.header ?? column.imex.key, // Assign key if header is missing
            key: column.imex.key
          }
        })

      return { header, data }
    } catch (e) {
      console.error('Export error:', e)
      this._showToast(e)
    }
  }

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

window.customElements.define('billing-module-report', BillingModuleReport)
