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 { i18next, localize } from '@things-factory/i18n-base'
import { client, gqlContext, PageView, store } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

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 AnalysisPickingPackingReport 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,
      _gristData: Object,
      data: Object
    }
  }

  get context() {
    return {
      title: i18next.t('title.analytics_report'),
      exportable: {
        name: i18next.t('title.analytics_report'),
        data: this._exportableData.bind(this)
      },
      help: ''
    }
  }

  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]')
  }

  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 searchFields() {
    const sortingOptions = [
      { name: i18next.t('label.desc'), value: 'desc' },
      { name: i18next.t('label.asc'), value: 'asc' }
    ]

    const sortingTypes = [
      { name: i18next.t('label.packing'), value: 'packing' },
      { name: i18next.t('label.picking'), value: 'picking' }
    ]

    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()),
        handlers: { change: this._submit.bind(this) }
      },
      {
        label: i18next.t('field.name'),
        name: 'name',
        type: 'string',
        props: { searchOper: 'custom' }
      },
      {
        label: i18next.t('field.rate'),
        name: 'rate',
        type: 'select',
        options: sortingOptions,
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.type'),
        name: 'type',
        type: 'select',
        options: sortingTypes,
        props: { searchOper: 'eq' }
      }
    ]
  }

  get reportConfig() {
    const getTimeRangeHeader = hour => {
      const now = new Date()
      now.setHours(hour)
      const next = new Date(now)
      next.setHours(now.getHours() + 1)
      return `${now.toLocaleString('en-US', { hour: 'numeric', hour12: true })} - ${next.toLocaleString('en-US', {
        hour: 'numeric',
        hour12: true
      })}`
    }

    const timeRangeColumns = Array.from({ length: 12 }, (_, i) => {
      const startHour = i + 7
      const header = getTimeRangeHeader(startHour)
      return {
        type: 'string',
        name: `${startHour}`,
        header: header,
        record: { editable: false, align: 'center' },
        width: 120
      }
    })

    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'string',
        name: 'name',
        header: i18next.t('field.name'),
        width: 200
      },
      ...timeRangeColumns, // Using the time range columns array directly
      {
        type: 'float',
        name: 'totalDaysWorked',
        header: i18next.t('field.total_days_worked'),
        width: 160
      },
      {
        type: 'float',
        name: 'totalPacks',
        header: i18next.t('field.total_pack'),
        width: 110,
        align: 'center'
      },
      {
        type: 'float',
        name: 'totalHoursWorked',
        header: i18next.t('field.total_hours_worked'),
        width: 170
      },
      {
        type: 'float',
        name: 'packingRate',
        header: i18next.t('field.packing_rate'),
        width: 150
      }
    ]

    let list = {
      fields: [
        'name',
        '7AM-8AM',
        '8AM-9AM',
        '9AM-10AM',
        '10AM-11AM',
        '11AM-12PM',
        '12PM-1PM',
        '1PM-2PM',
        '2PM-3PM',
        '3PM-4PM',
        '4PM-5PM',
        '5PM-6PM',
        '6PM-7PM',
        'totalDaysWorked',
        'totalPacks',
        'totalHoursWorked',
        'packingRate'
      ]
    }

    return {
      columns: columns,
      list,
      pagination: { limit: 50, pages: [100, 200, 500, 1000] },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      }
    }
  }

  async pageInitialized() {
    this._gristData = { total: 0, records: [] }
    const [_partnersReq] = await Promise.allSettled([this._fetchPartners()])

    this._partners = _partnersReq.status == 'fulfilled' ? _partnersReq.value : []

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

  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)
            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 pagination = { page, limit }
      const sortings = sorters

      const response = await client.query({
        query: gql`
          query analysisPickingPackingReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            analysisPickingPackingReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                name
                hourlyData
                totalDaysWorked
                totalPacks
                totalHoursWorked
                packingRate
              }
              total
            }
          }
        `,
        variables: { filters, pagination, sortings },
        context: gqlContext()
      })

      const data = {
        total: response.data.analysisPickingPackingReport.total,
        records:
          response.data.analysisPickingPackingReport.items.map(i => {
            let hourlyData = JSON.parse(i.hourlyData)
            return {
              ...i,
              ...hourlyData
            }
          }) || []
      }

      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
    this._submit()
  }

  _submit(e) {
    this._config = { ...this.reportConfig }
    this.searchForm.submit()
  }

  async _exportableData() {
    try {
      const getTimeRangeHeader = hour => {
        const now = new Date()
        now.setHours(hour)
        const next = new Date(now)
        next.setHours(now.getHours() + 1)
        return `${now.toLocaleString('en-US', { hour: 'numeric', hour12: true })} - ${next.toLocaleString('en-US', {
          hour: 'numeric',
          hour12: true
        })}`
      }

      const timeRangeColumns = Array.from({ length: 12 }, (_, i) => {
        const startHour = i + 7
        const header = getTimeRangeHeader(startHour)
        const key = `${startHour}`
        return {
          type: 'number',
          name: `${startHour}`,
          header: header,
          key: key,
          record: { editable: false, align: 'center' },
          width: 20
        }
      })

      const headerSetting = [
        { header: i18next.t('field.name'), key: 'name', width: 30, type: 'string' },
        ...timeRangeColumns,
        { header: i18next.t('field.total_days_worked'), key: 'totalDaysWorked', width: 30, type: 'float' },
        { header: i18next.t('field.total_pack'), key: 'totalPacks', width: 30, type: 'float' },
        { header: i18next.t('field.total_hours_worked'), key: 'totalHoursWorked', width: 30, type: 'float' },
        { header: i18next.t('field.packing_rate'), key: 'packingRate', width: 30, type: 'float' }
      ]

      let data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records.map(itm => {
        const hourlyData = JSON.parse(itm.hourlyData) // Parse the hourly data from JSON
        const timeRangeData = Array.from({ length: 12 }, (_, i) => {
          const startHour = i + 7
          const key = `${startHour}`
          const value = parseFloat(hourlyData[startHour.toString()]) || 0 // Convert to number
          return {
            [key]: value
          }
        }).reduce((obj, item) => ({ ...obj, ...item }), {})

        return {
          ...timeRangeData,
          name: itm.name,
          totalDaysWorked: itm.totalDaysWorked,
          totalPacks: itm.totalPacks,
          totalHoursWorked: itm.totalHoursWorked,
          packingRate: itm.packingRate
        }
      })

      var exportData = {
        header: [...headerSetting],
        data
      }

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

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

window.customElements.define('analysis-picking-packing-report', AnalysisPickingPackingReport)
