<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import type IUser from '@/models/IUser'
import { useUserStore } from '@/stores/user'

const newUser = defineModel<IUser>({ required: true })
defineEmits<{ remove: [] }>()
const { t } = useI18n()

const userStore = useUserStore()
const { user } = storeToRefs(userStore)

const localeUserId = ref<string>((newUser.value.userId || '').toLowerCase())

const userId = computed({
  get: () => localeUserId.value,
  set: (val: string) => {
    localeUserId.value = (val || '').toLowerCase()
  }
})

watch(
  localeUserId,
  (value) => {
    if (newUser.value.userId !== value) {
      newUser.value.userId = value
    }
  },
  { immediate: true }
)

const isMainUser = computed(
  () => !!user.value && !!newUser.value && user.value.userId === newUser.value.userId
)

const maxChar = (u: IUser): number => 20 - (u.alias ? u.alias.length : 0)
</script>

<template>
  <div class="user-new card bg-base-100 shadow p-4 my-2 flex flex-col md:flex-row gap-3 items-end">
    <div v-if="user" class="flex flex-col gap-1 flex-1">
      <label class="label">{{ t('user.pseudo') }}</label>
      <input
        v-model="userId"
        :readonly="isMainUser"
        type="text"
        class="input input-bordered w-full"
      />
    </div>
    <div v-if="newUser" class="flex flex-col gap-1 flex-1">
      <label class="label">{{ t('user.alias') }}</label>
      <input
        v-model="newUser.alias"
        required
        type="text"
        maxlength="20"
        :placeholder="newUser.userId"
        class="input input-bordered w-full"
      />
      <p class="text-xs text-primary">Nom utilisé sur ce compte</p>
      <p class="text-xs text-primary">
        {{ t('validation.max_char', { max: maxChar(newUser) }, maxChar(newUser)) }}
      </p>
    </div>
    <button
      v-if="!isMainUser"
      class="btn btn-error btn-square"
      @click="$emit('remove')"
    >
      <vaquant-icon icon="trash" />
    </button>
  </div>
</template>
