import { defineComponent, ref, watch } from 'vue'
import { useUiTheme } from '../theme'
import { renderToolSettingsDialog } from './tool-settings-dialog/render'

export const DimSdkToolSettingsDialog = defineComponent({
  name: 'DimSdkToolSettingsDialog',
  props: {
    modelValue: { type: Boolean, required: true },
    w: { type: Number, default: 48 },
    h: { type: Number, default: 16 },
    backdrop: { type: Boolean, default: false },
    title: { type: String, default: undefined },
    apiKeyDraft: { type: String, required: true },
    apiKeyMasked: { type: String, required: true },
  },
  emits: {
    'update:modelValue': (_v: boolean) => true,
    'update:apiKeyDraft': (_v: string) => true,
    apply: () => true,
    cancel: () => true,
  },
  setup(props, { emit }) {
    const ui = useUiTheme()
    const focusedField = ref<'apiKey' | null>(null)

    watch(
      () => props.modelValue,
      (open) => {
        focusedField.value = open ? 'apiKey' : null
      },
      { immediate: true },
    )

    return () => {
      return renderToolSettingsDialog(
        {
          modelValue: props.modelValue,
          w: props.w,
          h: props.h,
          backdrop: props.backdrop,
          title: props.title,
          apiKeyDraft: props.apiKeyDraft,
          apiKeyMasked: props.apiKeyMasked,
          focusedField: focusedField.value,
        },
        {
          updateModelValue: (v: boolean) => emit('update:modelValue', v),
          updateApiKeyDraft: (v: string) => emit('update:apiKeyDraft', v),
          setFocusedField: (v: 'apiKey' | null) => {
            focusedField.value = v
          },
          apply: () => emit('apply'),
          cancel: () => emit('cancel'),
        },
        ui,
      )
    }
  },
})
