<script setup lang='ts'>
import {LDNormalModal, LDErrorBoundary, LDSuspenseLoading} from '@components';
import {toRefs} from 'vue';
import {useVModel} from '@vueuse/core';
import {useFormState} from './hooks';
import {useI18n} from 'vue-i18n';
import ErrorBoundary from 'veboundary';
import Info from './Info.vue';

defineOptions({name: 'UserPageModal'});

type Props = {
  visible: boolean;
  id: string;
  onFetch: () => void;
};

const props = defineProps<Props>();
const {visible, id} = toRefs(props);
const emits = defineEmits<{(event: 'update:visible'): void}>();
const visibleValue = useVModel(props, 'visible', emits);
const [isLoading, {onSubmit, setValues}] = useFormState(
  id,
  visible,
  {
    onFetch: props.onFetch,
    onClose() {
      visibleValue.value = false;
    },
  },
);

const {t} = useI18n();
</script>

<template>
  <LDNormalModal
    :isAdd="id.length === 0"
    v-model="visibleValue"
    :title="t(`user.modal.title[${id.length > 0 ? 1 : 0}]`)"
    @submit="onSubmit"
    :isLoading="isLoading"
  >
    <ErrorBoundary propagation>
      <template #fallback="{error, reset}">
        <LDErrorBoundary :msg="error.message" @reset="reset" />
      </template>

      <Suspense>
        <template #fallback>
          <LDSuspenseLoading />
        </template>

        <Info :id="id" :setValues="setValues" />
      </Suspense>
    </ErrorBoundary>
  </LDNormalModal>
</template>

