<script setup lang="ts">
import { ref, watch } from 'vue'
import { isNumber } from 'is-what'
import { copy } from 'copy-anything'
import { dbUsers, defaultsUser } from './dbUsers'
import CFormChangeEditable from './CFormChangeEditable.vue'
import CFormWrapper from '../../../CFormWrapper/CFormWrapper.vue'
import { openModalSpinner } from '../../../CModalConfirmation/helpers'

const props = defineProps({
  docId: { type: String, default: undefined },
})

const emit = defineEmits({
  hide: () => true,
})
// もしくは
// const emit = defineEmits<{
//   (e: 'hide'): void
// }>()

const mode: 'edit' | 'add' = props.docId ? 'edit' : 'add'

const localData = ref(defaultsUser())
const localId = props.docId || Math.random().toString()

if (mode === 'add') {
  localData.value.id = localId
}
if (mode === 'edit' && props.docId) {
  // fetch data from server
  dbUsers
    .doc(props.docId)
    .fetch()
    .then((user) => {
      if (user) localData.value = copy(user)
    })
}

const validation = {
  name: {
    error: (val: any) => {
      if (!val) return '会社名を記入してください'
      return null
    },
  },
}

async function save() {
  // console.log(`こちらのデータを保存 → `, localData.value)
  const hideSpinner = openModalSpinner()
  await new Promise((resolve) => setTimeout(resolve, 1000))
  await dbUsers.doc(localId).merge(localData.value)
  hideSpinner()
  emit('hide')
}
const flag = ref(mode === 'add')
// watch(flag, (newVal) => console.log(newVal))
</script>

<template>
  <CFormWrapper
    v-slot="{ fieldProps, errorsPerField }"
    v-model="localData"
    v-model:editFlag="flag"
    :mode="mode"
    :validation="validation"
    @save="() => save()"
    @cancel="() => (mode === 'add' ? emit('hide') : undefined)"
    @close="() => emit('hide')"
  >
    <CFormChangeEditable
      v-model="localData"
      v-model:editFlag="flag"
      :fieldProps="fieldProps"
      :mode="mode"
      :errorsPerField="errorsPerField"
    />
  </CFormWrapper>
</template>
