import type { ChatPageContext } from '../../context'
import { t } from '#cli/i18n'
import { h } from 'vue'
import { DimSdkSessionsDialog } from '../../../../ui/components/SessionsDialog'
import { DimSdkSwitchSessionDialog } from '../../../../ui/components/SwitchSessionDialog'

export function renderSessionsOverlay(ctx: ChatPageContext) {
  return [
    h(DimSdkSessionsDialog, {
      w: ctx.configW.value,
      h: ctx.configH.value,
      modelValue: ctx.showSessions.value,
      suspendKeyboard: ctx.showSwitchConfirm.value,
      'onUpdate:modelValue': (v: boolean) => {
        ctx.showSessions.value = v
        if (!v) ctx.sessionsDeleteArmed.value = false
      },
      loading: ctx.sessionsLoading.value,
      deleteArmed: ctx.sessionsDeleteArmed.value,
      cwdOnly: ctx.sessionsCwdOnly.value,
      'onUpdate:cwdOnly': (v: boolean) => {
        ctx.sessionsCwdOnly.value = v
        ctx.sessionsDeleteArmed.value = false
      },
      currentCwd: String((ctx.store.state as any)?.context?.cwd ?? ''),
      activeSessionId: String(ctx.store.state.sessionId ?? ''),
      allSessionsCount: ctx.sessionsAllCount.value,
      sessions: ctx.sessionsList.value,
      selectedIndex: ctx.sessionsIndex.value,
      'onUpdate:selectedIndex': (v: number) => {
        ctx.sessionsIndex.value = v
        ctx.sessionsDeleteArmed.value = false
      },
      onOpen: async () => {
        await ctx.openSelectedSession()
      },
      onDelete: async () => {
        const api = ctx.sessionsApi
        const picked = ctx.sessionsList.value[ctx.sessionsIndex.value]
        if (!api || !picked) return
        const prevIndex = ctx.sessionsIndex.value
        if (!ctx.sessionsDeleteArmed.value) {
          ctx.sessionsDeleteArmed.value = true
          ctx.showCopyToast(t('homePage.toast.deleteConfirm'))
          return
        }
        ctx.sessionsDeleteArmed.value = false
        await api.delete(picked.id)
        await ctx.refreshSessions({ preferIndex: prevIndex })
      },
      onRefresh: async () => {
        ctx.sessionsDeleteArmed.value = false
        await ctx.refreshSessions()
      },
    }),
    h(DimSdkSwitchSessionDialog, {
      w: ctx.smW.value,
      h: ctx.smH.value,
      modelValue: ctx.showSwitchConfirm.value,
      'onUpdate:modelValue': (v: boolean) => {
        ctx.showSwitchConfirm.value = v
        if (!v) ctx.cancelSwitch()
      },
      title: ctx.switchConfirmTitle.value,
      targetLabel: ctx.switchConfirmTargetLabel.value,
      reason: ctx.switchConfirmReason.value,
      onConfirm: () => void ctx.confirmSwitch(),
    }),
  ]
}
