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

export const DimSdkRedoConfirmDialog = defineComponent({
  name: 'DimSdkRedoConfirmDialog',
  props: {
    modelValue: { type: Boolean, required: true },
    w: { type: Number, default: 56 },
    h: { type: Number, default: 10 },
  },
  emits: {
    'update:modelValue': (_v: boolean) => true,
    confirm: () => true,
    cancel: () => true,
  },
  setup(props, { emit }) {
    const ui = useUiTheme()
    function cancel() {
      emit('update:modelValue', false)
      emit('cancel')
    }

    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 textStyle = ui.style(['dialog.chrome', 'text.primary'])

      return h(
        TDialog as any,
        {
          modelValue: props.modelValue,
          'onUpdate:modelValue': (v: boolean) => emit('update:modelValue', v),
          onKeydownCapture: (e: any) => {
            // Prevent accidental text input / IME while this confirm dialog is open.
            if (
              typeof e?.key === 'string' &&
              e.key.length === 1 &&
              !e.ctrlKey &&
              !e.metaKey &&
              !e.altKey
            ) {
              e.preventDefault?.()
              e.stopPropagation?.()
            }
          },
          w: dialogW,
          h: dialogH,
          title: t('redoConfirmDialog.title'),
          placement: 'center',
          backdrop: false,
          padding: 1,
          style: ui.style(['dialog.chrome']),
          buttons: [
            { label: t('common.cancel'), value: 'cancel' },
            {
              label: t('common.confirm'),
              value: 'confirm',
              kind: 'primary',
              default: true,
            },
          ],
          onConfirm: (btn: any) => {
            if (btn?.value === 'confirm') {
              emit('confirm')
              emit('update:modelValue', false)
            } else {
              cancel()
            }
          },
          onClose: cancel,
        },
        () => [
          h(TText, {
            x: 0,
            y: 0,
            w: innerW,
            h: innerH,
            value: '',
            style: bodyStyle,
          }),
          h(TText, {
            x: 0,
            y: 1,
            w: innerW,
            value: t('redoConfirmDialog.body'),
            style: textStyle,
          }),
        ],
      )
    }
  },
})
