<script setup lang="ts">
import { PropType, ref, watch } from 'vue'
import { copy } from 'copy-anything'
import CInput from '../../../CInput/CInput.vue'
import CButton from '../../../CButton/CButton.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 },
  editFlag: { type: Boolean },
  mode: { type: String },
})
// Emitの定義
const emit = defineEmits<{
  (e: 'update:modelValue', payload: User): void
  (e: 'update:editFlag', payload: boolean): void
}>()

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

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

<template>
  <div class="c_form_user">
    <CInput
      v-bind="fieldProps"
      v-model="localValue.name"
      :p_Error="!!errorsPerField.name"
      class="_name"
      p_Title="名前"
    />
    <CButton @click="clickFlag" />
  </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>
