import { createEffect, on } from "solid-js"
import { bell } from "@/saeeol/bell"
import { SessionRetry } from "@/session/retry"
import { DialogGoUpsell } from "../../component/dialog-go-upsell"

const GO_UPSELL_LAST_SEEN_AT = "go_upsell_last_seen_at"
const GO_UPSELL_DONT_SHOW = "go_upsell_dont_show"
const GO_UPSELL_WINDOW = 86_400_000

interface BellDeps {
  sessionID: string
  getStatusType: () => string | undefined
  getPermissionsLen: () => number
  getQuestionsLen: () => number
  getSuggestionsNetworkLen: () => number
  bellEnabled: () => boolean
}

export function useBellEffects(d: BellDeps) {
  createEffect(
    on(
      () => [d.sessionID, d.getStatusType()] as const,
      ([id, type], prev) => {
        if (!prev || prev[0] !== id) return
        if (prev[1] && prev[1] !== "idle" && type === "idle" && d.bellEnabled()) bell()
      },
    ),
  )
  for (const getLen of [d.getPermissionsLen, d.getQuestionsLen, d.getSuggestionsNetworkLen]) {
    createEffect(
      on(() => [d.sessionID, getLen()] as const, ([id, len], prev) => {
        if (!prev || prev[0] !== id) return
        if (len > prev[1] && d.bellEnabled()) bell()
      }),
    )
  }
}

interface UpsellDeps {
  sessionID: string
  event: { on: (type: any, handler: (evt: any) => void) => void }
  dialog: { stack: unknown[]; [key: string]: any }
  kv: { get: (key: string) => unknown; set: (key: string, value: unknown) => void }
}

export function useUpsellHandler(d: UpsellDeps) {
  d.event.on("session.status", (evt) => {
    if (evt.properties.sessionID !== d.sessionID) return
    if (evt.properties.status.type !== "retry") return
    if (evt.properties.status.message !== SessionRetry.GO_UPSELL_MESSAGE) return
    if (d.dialog.stack.length > 0) return
    const seen = d.kv.get(GO_UPSELL_LAST_SEEN_AT)
    if (typeof seen === "number" && Date.now() - seen < GO_UPSELL_WINDOW) return
    if (d.kv.get(GO_UPSELL_DONT_SHOW)) return
    void DialogGoUpsell.show(d.dialog as any).then((dontShowAgain) => {
      if (dontShowAgain) d.kv.set(GO_UPSELL_DONT_SHOW, true)
      d.kv.set(GO_UPSELL_LAST_SEEN_AT, Date.now())
    })
  })
}
