<script setup lang="ts">
import { PropType, ref, watch } from 'vue'
import { copy } from 'copy-anything'
import CInput from '../../../CInput/CInput.vue'
import { User } from './dbUsers'
import { FieldProps, ErrorsPerField } from '../../../CFormWrapper/CFormWrapper.types'

const props = defineProps({
  modelValue: { type: Object as PropType<User>, required: true },
  fieldProps: { type: Object as PropType<FieldProps>, required: true },
  errorsPerField: { type: Object as PropType<ErrorsPerField>, required: true },
})
// Emitの定義
const emit = defineEmits<{
  (e: 'update:modelValue', payload: User): void
}>()

const localValue = ref(copy(props.modelValue))

watch(localValue, (newVal) => emit('update:modelValue', newVal), { deep: true })
watch(
  () => props.modelValue,
  (newVal) => (localValue.value = newVal),
  { deep: true }
)
</script>

<template>
  <div class="c_form_user">
    <CInput
      v-bind="fieldProps"
      v-model="localValue.name"
      :p_Error="!!errorsPerField.name"
      class="_name"
      p_Title="名前"
    />
  </div>
</template>

<style lang="scss" scoped>
.c_form_user {
  grid-template-areas: 'name';
}
</style>
<style lang="sass" scoped>
.c_form_user
  display: grid
  grid-gap: 1rem 2rem
  grid-template-columns: 1fr
._name
  grid-area: name
</style>
