/**
 * Switch-session confirmation dialog.
 *
 * Shown when the user attempts to switch/create a session while the current one is busy
 * (streaming response, pending approval, or ask_user pause).
 */

import { t } from '#cli/i18n'
import { TDialog, TText, useTerminal } from '@simon_he/vue-tui'
import { defineComponent, h, watch } from 'vue'
import { useUiTheme } from '../theme'

export const DimSdkSwitchSessionDialog = defineComponent({
  name: 'DimSdkSwitchSessionDialog',
  props: {
    modelValue: { type: Boolean, required: true },
    title: { type: String, default: '' },
    targetLabel: { type: String, default: '' },
    reason: { type: String, default: '' },
    w: { type: Number, default: 56 },
    h: { type: Number, default: 10 },
  },
  emits: {
    'update:modelValue': (_v: boolean) => true,
    confirm: () => true,
  },
  setup(props, { emit }) {
    const ui = useUiTheme()
    const { events, scheduler } = useTerminal()
    const dialogZ = 1300

    function focusDefaultSwitchNode(attempt = 0): void {
      if (!props.modelValue) return
      const manager: any = events.value
      if (
        !manager ||
        typeof manager.debugNodes !== 'function' ||
        typeof manager.focus !== 'function'
      ) {
        if (attempt < 10)
          queueMicrotask(() => focusDefaultSwitchNode(attempt + 1))
        return
      }
      const nodes = (manager.debugNodes?.() ?? [])
        .filter((n: any) => {
          return !!(
            n?.visible &&
            n?.focusable &&
            (n?.zIndex ?? 0) >= dialogZ + 1
          )
        })
        .sort((a: any, b: any) => {
          const za = a?.zIndex ?? 0
          const zb = b?.zIndex ?? 0
          if (zb !== za) return zb - za
          const ay = a?.rect?.y ?? 0
          const by = b?.rect?.y ?? 0
          if (by !== ay) return by - ay
          return (b?.rect?.x ?? 0) - (a?.rect?.x ?? 0)
        })
      const target = nodes[0]
      if (!target?.id) {
        if (attempt < 10)
          queueMicrotask(() => focusDefaultSwitchNode(attempt + 1))
        return
      }
      manager.focus(target.id)
      scheduler.invalidate()
    }

    watch(
      () => props.modelValue,
      (open) => {
        if (!open) return
        queueMicrotask(() => {
          queueMicrotask(() => {
            focusDefaultSwitchNode(0)
          })
        })
      },
    )

    return () => {
      if (!props.modelValue) return null

      const dialogW = Math.max(40, Math.floor(props.w))
      const dialogH = Math.max(8, Math.floor(props.h))
      const innerW = Math.max(0, dialogW - 4)
      const innerH = Math.max(0, dialogH - 4)
      const bodyStyle = ui.style(['dialog.chrome'])
      const titleStyle = ui.style(['dialog.chrome', 'status.warning'])
      const mutedStyle = ui.style(['dialog.chrome', 'text.muted'])

      const target = String(props.targetLabel ?? '').trim()
      const reason = String(props.reason ?? '').trim()

      return h(
        TDialog as any,
        {
          modelValue: props.modelValue,
          'onUpdate:modelValue': (v: boolean) => emit('update:modelValue', v),
          onKeydownCapture: (e: any) => {
            if (e?.key === 'Escape') {
              e.preventDefault?.()
              e.stopPropagation?.()
              emit('update:modelValue', false)
              return
            }
            if (
              typeof e?.key === 'string' &&
              e.key.length === 1 &&
              !e.ctrlKey &&
              !e.metaKey &&
              !e.altKey
            ) {
              e.preventDefault?.()
              e.stopPropagation?.()
            }
          },
          w: dialogW,
          h: dialogH,
          title:
            String(props.title ?? '').trim() || t('switchSessionDialog.title'),
          placement: 'center',
          zIndex: dialogZ,
          backdrop: false,
          padding: 1,
          style: ui.style(['dialog.chrome']),
          buttons: [
            { label: t('common.cancel'), value: 'cancel' },
            {
              label: t('switchSessionDialog.confirm'),
              value: 'confirm',
              kind: 'primary',
              default: true,
            },
          ],
          onConfirm: (btn: any) => {
            if (btn?.value === 'confirm') emit('confirm')
            emit('update:modelValue', false)
          },
          onClose: () => emit('update:modelValue', false),
        },
        () => [
          h(TText, {
            x: 0,
            y: 0,
            w: innerW,
            h: innerH,
            value: '',
            style: bodyStyle,
          }),
          h(TText, {
            x: 0,
            y: 0,
            w: innerW,
            wrap: true,
            value: target
              ? t('switchSessionDialog.target', { target })
              : t('switchSessionDialog.fallback'),
            style: titleStyle,
          }),
          h(TText, {
            x: 0,
            y: 2,
            w: innerW,
            wrap: true,
            value: t('switchSessionDialog.warning'),
            style: mutedStyle,
          }),
          reason
            ? h(TText, {
                x: 0,
                y: 4,
                w: innerW,
                wrap: true,
                value: t('switchSessionDialog.reason', { reason }),
                style: mutedStyle,
              })
            : null,
        ],
      )
    }
  },
})
