<script setup lang="ts">
import { NCheckbox, NSelect } from 'naive-ui'
import { computed, ref, watch } from 'vue'

import { listRegions, subscribeRegion } from '@/api/configs'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import { useAsync } from '@/composables/useAsync'
import { useToast } from '@/composables/useToast'

const props = defineProps<{
  show: boolean
  cfgId: number
  subscribedKeys: string[]
  /** 从区域列表行内发起时预选并锁定该区域 */
  presetKey?: string | null
}>()
const emit = defineEmits<{ 'update:show': [boolean]; subscribed: [] }>()

const message = useToast()
const submitting = ref(false)
const regionKey = ref<string | null>(null)
const acknowledged = ref(false)

const regions = useAsync(listRegions, false)

watch(
  () => props.show,
  (v) => {
    if (v) {
      regionKey.value = props.presetKey ?? null
      acknowledged.value = false
      void regions.run()
    }
  },
)

const options = computed(
  () =>
    regions.data.value
      ?.filter((r) => !props.subscribedKeys.includes(r.key))
      .map((r) => ({ label: `${r.alias}（${r.name}）`, value: r.key })) ?? [],
)

async function submit() {
  if (!regionKey.value) return
  submitting.value = true
  try {
    await subscribeRegion(props.cfgId, regionKey.value)
    message.success('订阅请求已提交，生效需数分钟（状态 IN_PROGRESS）')
    emit('update:show', false)
    emit('subscribed')
  } catch (e) {
    message.error(e instanceof Error ? e.message : '订阅失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <FormModal
    :show="show"
    title="订阅新区域"
    :submitting="submitting"
    :submit-disabled="!regionKey || !acknowledged"
    submit-text="确认订阅"
    danger
    @update:show="emit('update:show', $event)"
    @submit="submit"
  >
    <div
      class="mb-3.5 rounded-md border border-err/30 bg-err/10 px-3.5 py-2.5 text-[12.5px] leading-relaxed text-err"
    >
      区域订阅一经创建<strong>永久不可取消</strong>，会永久占用该租户的区域配额并可能产生跨区域数据驻留影响。请确认业务确实需要后再操作。
    </div>
    <FormField label="目标区域" required :hint="presetKey ? undefined : '已订阅的区域不在列表中'">
      <NSelect
        v-model:value="regionKey"
        filterable
        :disabled="!!presetKey"
        :options="options"
        :loading="regions.loading.value"
        placeholder="选择要订阅的区域"
      />
    </FormField>
    <NCheckbox v-model:checked="acknowledged">我已知晓区域订阅不可取消</NCheckbox>
  </FormModal>
</template>
