import type { IHeaderComp, IHeaderParams } from 'ag-grid-community'
import { i18n } from '@/i18n'

export type ResetHeaderParams = IHeaderParams & {
  onReset?: () => void | Promise<void>
  resetTitle?: string
}

export class AgGridResetHeader implements IHeaderComp {
  private params!: ResetHeaderParams
  private eGui!: HTMLDivElement
  private eLabel!: HTMLSpanElement
  private eButton!: HTMLButtonElement
  private onButtonClick = (event: MouseEvent) => {
    event.preventDefault()
    event.stopPropagation()
    void this.params.onReset?.()
  }

  init(params: ResetHeaderParams) {
    this.params = params

    const eGui = document.createElement('div')
    eGui.style.display = 'flex'
    eGui.style.alignItems = 'center'
    eGui.style.justifyContent = 'space-between'
    eGui.style.gap = '6px'
    eGui.style.width = '100%'

    const eLabel = document.createElement('span')
    eLabel.style.flex = '1'
    eLabel.style.minWidth = '0'
    eLabel.style.whiteSpace = 'normal'
    eLabel.style.lineHeight = '1.2'

    const eButton = document.createElement('button')
    eButton.type = 'button'
    eButton.textContent = '↻'
    const fallbackResetTitle = i18n.global.t('agGrid.resetDefault')
    eButton.setAttribute('aria-label', params.resetTitle || fallbackResetTitle)
    eButton.style.display = 'inline-flex'
    eButton.style.alignItems = 'center'
    eButton.style.justifyContent = 'center'
    eButton.style.width = '18px'
    eButton.style.height = '18px'
    eButton.style.border = '1px solid #d1d5db'
    eButton.style.borderRadius = '999px'
    eButton.style.background = '#fff'
    eButton.style.color = '#4b5563'
    eButton.style.cursor = 'pointer'
    eButton.style.fontSize = '12px'
    eButton.style.lineHeight = '1'
    eButton.style.flex = '0 0 auto'
    eButton.addEventListener('click', this.onButtonClick)

    eGui.append(eLabel, eButton)

    this.eGui = eGui
    this.eLabel = eLabel
    this.eButton = eButton
    this.refresh(params)
  }

  getGui() {
    return this.eGui
  }

  refresh(params: ResetHeaderParams) {
    this.params = params
    this.eLabel.textContent = params.displayName || params.column?.getColDef().headerName || ''
    const fallbackResetTitle = i18n.global.t('agGrid.resetDefault')
    this.eButton.setAttribute('aria-label', params.resetTitle || fallbackResetTitle)
    this.eButton.style.visibility = params.onReset ? 'visible' : 'hidden'
    return true
  }

  destroy() {
    this.eButton?.removeEventListener('click', this.onButtonClick)
  }
}
