import {Tooltip, TooltipView} from "@bokehjs/models/ui/tooltip"
import { build_view, IterViews} from "@bokehjs/core/build_views"
import * as p from "@bokehjs/core/properties"

import {
  CheckboxButtonGroup as bkCheckboxButtonGroup,
  CheckboxButtonGroupView as bkCheckboxButtonGroupView,
} from '@bokehjs/models/widgets/checkbox_button_group'


export class CheckboxButtonGroupView extends bkCheckboxButtonGroupView {
  declare model: CheckboxButtonGroup

  protected tooltip: TooltipView | null

  override *children(): IterViews {
    yield* super.children()
    if (this.tooltip != null)
      yield this.tooltip
  }

  override async lazy_initialize(): Promise<void> {
    await super.lazy_initialize()
    const {tooltip} = this.model
    if (tooltip != null)
      this.tooltip = await build_view(tooltip, {parent: this})
  }

  override remove(): void {
    this.tooltip?.remove()
    super.remove()
  }

  override render(): void {
    super.render()

    const toggle = (visible: boolean) => {
      this.tooltip?.model.setv({
        visible,
      })
    }
    this.el.addEventListener("mouseenter", () => {
      toggle(true)
    })
    this.el.addEventListener("mouseleave", () => {
      toggle(false)
    })
  }

}

export namespace CheckboxButtonGroup {
  export type Attrs = p.AttrsOf<Props>

  export type Props = bkCheckboxButtonGroup.Props & {
    tooltip: p.Property<Tooltip | null>
  }
}

export interface CheckboxButtonGroup extends CheckboxButtonGroup.Attrs {}

export class CheckboxButtonGroup extends bkCheckboxButtonGroup {
  declare properties: CheckboxButtonGroup.Props
  declare __view_type__: CheckboxButtonGroupView

  static __module__ = "panel.models.widgets"

  constructor(attrs?: Partial<CheckboxButtonGroup.Attrs>) {
    super(attrs)
  }

  static {
    this.prototype.default_view = CheckboxButtonGroupView

    this.define<CheckboxButtonGroup.Props>(({Nullable, Ref}) => ({
      tooltip: [ Nullable(Ref(Tooltip)), null ],
    }))
  }
}
