<script setup lang="ts">
import type { configAlarmApi } from '#/api';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Button } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { updateAlarmConfig } from '#/api';
import { $t } from '#/locales';

import { useEditSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<configAlarmApi.Alarm>();
const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: useEditSchema(),
  showDefaultActions: false,
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues(formData.value || {});
}

const [Drawer, modalApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues<configAlarmApi.Alarm>();
      await updateAlarmConfig(data?.id, {
        config: {
          key: data.key,
          value: data.value,
        },
      });
      // console.warn('user data', data);
      try {
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<configAlarmApi.Alarm>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
      }
    }
  },
});
</script>

<template>
  <Drawer>
    <Form>
      <template #prepend-footer>
        <div class="flex-auto">
          <Button type="primary" danger @click="resetForm">
            {{ $t('common.reset') }}
          </Button>
        </div>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped></style>
