<script setup lang="ts">
import AppInputNumber from '@/components/AppInputNumber.vue'
import { reactive, ref, watch } from 'vue'

import { updateBootVolume } from '@/api/bootVolumes'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import type { BootVolume } from '@/types/api'
import { useToast } from '@/composables/useToast'

const props = defineProps<{
  show: boolean
  cfgId: number
  region?: string
  bootVolume: BootVolume | null
}>()
const emit = defineEmits<{ 'update:show': [boolean]; updated: [] }>()

const message = useToast()
const submitting = ref(false)
const form = reactive({ sizeInGBs: 50, vpusPerGB: 10 })

watch(
  () => props.show,
  (v) => {
    if (!v || !props.bootVolume) return
    form.sizeInGBs = props.bootVolume.sizeInGBs
    form.vpusPerGB = props.bootVolume.vpusPerGB
  },
)

async function submit() {
  const bv = props.bootVolume
  if (!bv) return
  if (form.sizeInGBs < bv.sizeInGBs) {
    message.error('引导卷仅支持扩容，不能缩小')
    return
  }
  submitting.value = true
  try {
    await updateBootVolume(
      props.cfgId,
      bv.id,
      {
        sizeInGBs: form.sizeInGBs === bv.sizeInGBs ? 0 : form.sizeInGBs,
        vpusPerGB: form.vpusPerGB === bv.vpusPerGB ? 0 : form.vpusPerGB,
      },
      props.region,
    )
    message.success('修改已提交；扩容后需在实例 OS 内扩展文件系统')
    emit('update:show', false)
    emit('updated')
  } catch (e) {
    message.error(e instanceof Error ? e.message : '保存失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <FormModal
    :show="show"
    title="调整引导卷"
    :submitting="submitting"
    submit-text="保存"
    @update:show="emit('update:show', $event)"
    @submit="submit"
  >
    <div class="grid grid-cols-2 gap-3 max-md:grid-cols-1">
      <FormField label="大小（GB）" hint="仅支持扩容；扩容后需在 OS 内扩展文件系统">
        <AppInputNumber
v-model:value="form.sizeInGBs"
          :min="bootVolume?.sizeInGBs ?? 47"
          :max="32768"
          class="w-full"
        />
      </FormField>
      <FormField label="性能（VPU/GB）" hint="10 均衡 – 120 超高性能，可在线调整">
        <AppInputNumber v-model:value="form.vpusPerGB" :min="10" :max="120" :step="10" class="w-full" />
      </FormField>
    </div>
  </FormModal>
</template>
