<script setup lang="ts">
/**
 * @file ProfileEditForm.vue
 * @description ฟอร์มสำหรับแก้ไขข้อมูลส่วนตัวของผู้ใช้ (Form for editing user personal information)
 */

const props = defineProps<{
    modelValue: any; // userData (firstName, lastName, phone, etc.)
    loading: boolean;
    verifying?: boolean;
    flat?: boolean;
}>();

const emit = defineEmits<{
    (e: 'update:modelValue', value: any): void;
    (e: 'submit'): void;
    (e: 'upload', file: File): void;
    (e: 'verify'): void;
}>();

const { t } = useI18n();
const fileInput = ref<HTMLInputElement | null>(null);

const nameRules = [(val: string) => !!val || t('common.required')];
const emailRules = [
  (val: string) => !!val || t('common.required'),
  (val: string) => /.+@.+\..+/.test(val) || t('common.invalidEmail')
];
const phoneRules = [
  (val: string) => !!val || t('common.required'),
  (val: string) => /^0[0-9]{8,9}$/.test(val) || t('common.invalidPhone')
];

const triggerUpload = () => {
  fileInput.value?.click();
};

const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files[0]) {
    emit('upload', target.files[0]);
  }
};

const onPhoneInput = (val: string | number | null) => {
  let value = String(val || '');
  // กรองเฉพาะตัวเลขเผื่อการป้อนข้อมูลวิธีอื่น
  value = value.replace(/\D/g, '');
  if (value.length > 10) {
    value = value.substring(0, 10);
  }
  props.modelValue.phone = value;
};

const onPhoneKeydown = (e: KeyboardEvent) => {
  // อนุญาตให้กดปุ่มควบคุมต่างๆ ได้
  const controlKeys = ['Backspace', 'Tab', 'Enter', 'Escape', 'ArrowLeft', 'ArrowRight', 'Delete', 'v', 'c', 'a'];
  
  if (e.ctrlKey || e.metaKey) {
    if (controlKeys.includes(e.key.toLowerCase())) return;
  }

  // ป้องกันการกรอกตัวอักษร
  if (!controlKeys.includes(e.key) && !/^\d$/.test(e.key)) {
    e.preventDefault();
  }
};
</script>

<template>
    <div :class="[!flat ? 'card-premium p-6 md:p-8' : '']" class="h-fit">
        <div v-if="!flat" class="flex items-center gap-3 mb-8">
            <div class="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center">
                <q-icon name="person" class="text-blue-600 dark:text-blue-400 text-xl" />
            </div>
            <h2 class="text-xl font-black text-slate-900 dark:text-white">
                {{ $t('profile.editPersonalDesc') }}
            </h2>
        </div>

        <div class="flex flex-col gap-6">
        
        <div class="flex items-center gap-6">
            <div class="relative group cursor-pointer" @click="triggerUpload">
                <UserAvatar 
                :photo-u-r-l="modelValue.photoURL" 
                :first-name="modelValue.firstName" 
                :last-name="modelValue.lastName" 
                size="80"
                class="rounded-2xl border-2 border-slate-100 dark:border-white/10"
                />
            
                <div class="absolute inset-0 bg-black/40 rounded-2xl flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                    <q-icon name="camera_alt" class="text-white text-xl" />
                </div>
                <!-- ช่องเลือกไฟล์ที่ถูกซ่อนไว้ (Hidden Input) -->
                <input ref="fileInput" type="file" class="hidden" accept="image/*" @change="handleFileUpload" >
            </div>
            
            <div class="flex flex-col gap-2">
            <div class="font-bold text-slate-900 dark:text-white mb-1">{{ $t('profile.yourAvatar') }}</div>
            
            <!-- แถวปุ่มกด (Buttons Row) -->
                <div class="flex items-center gap-3">
                <template v-if="modelValue.photoURL">
                    <q-btn 
                        unelevated
                        rounded
                        color="primary" 
                        :label="$t('profile.changeAvatar')" 
                        class="font-bold shadow-lg shadow-blue-500/30"
                        @click="triggerUpload"
                    />
                </template>
                <template v-else>
                        <q-btn 
                        unelevated
                        rounded
                        color="primary" 
                        :label="$t('profile.uploadNew')" 
                        class="font-bold shadow-lg shadow-blue-500/30"
                        @click="triggerUpload"
                    />
                </template>
                </div>

            <!-- ข้อความจำกัดขนาดไฟล์ (Add Limit Text) -->
            <div class="mt-1 text-xs text-slate-500 dark:text-slate-400">
                {{ $t('profile.uploadLimit') }}
            </div>
            </div>
        </div>

        <q-separator class="bg-slate-100 dark:bg-white/5" />

        <q-form @submit="emit('submit')" class="flex flex-col gap-6">

        <div class="grid grid-cols-1 gap-4">
            <div class="space-y-1">
                <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.prefix') }}</label>
                <q-select
                v-model="modelValue.prefix"
                :options="[
                    { label: $t('profile.mr'), value: 'นาย' },
                    { label: $t('profile.mrs'), value: 'นาง' },
                    { label: $t('profile.miss'), value: 'นางสาว' }
                ]"
                emit-value
                map-options
                outlined
                dense
                rounded
                class="premium-q-input"
                popup-content-class="text-slate-900"
                />
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.firstName') }}</label>
                <q-input
                    v-model="modelValue.firstName"
                    outlined dense rounded
                    class="premium-q-input"
                    :rules="nameRules"
                    hide-bottom-space
                />
                </div>
                <div>
                <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.lastName') }}</label>
                <q-input
                    v-model="modelValue.lastName"
                    outlined dense rounded
                    class="premium-q-input"
                    :rules="nameRules"
                    hide-bottom-space
                />
                </div>
            </div>

            <div>
                <div class="flex justify-between items-end mb-1">
                <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.email') }}</label>

                </div>
                <q-input
                v-model="modelValue.email"
                type="email"
                outlined dense rounded
                class="premium-q-input"
                :rules="emailRules"
                    hide-bottom-space
                    readonly
                    :hint="$t('profile.emailHint')"
                >
                    <template v-slot:append>
                         <div v-if="modelValue.emailVerifiedAt" class="flex items-center gap-1">
                             <q-icon name="check_circle" color="positive" />
                             <span class="text-green-600 text-xs font-bold">{{ $t('profile.emailVerified') }}</span>
                         </div>
                         <q-btn
                            v-else
                            flat
                            dense
                            no-caps
                            color="negative"
                            icon="mark_email_read"
                            :label="$t('profile.verifyEmail')"
                            class="text-sm font-bold"
                            :loading="verifying"
                            @click="$emit('verify')"
                         />
                    </template>
                </q-input>
            </div>

            <div>
                <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.phone') }}</label>
                <q-input
                :model-value="modelValue.phone"
                @update:model-value="onPhoneInput"
                @keydown="onPhoneKeydown"
                outlined dense rounded
                class="premium-q-input"
                :rules="phoneRules"
                hide-bottom-space
                maxlength="10"
                />
            </div>
        </div>

        <div class="pt-2">
            <q-btn
            type="submit"
            unelevated
            rounded
            color="primary"
            class="w-full py-3 font-bold text-base shadow-lg shadow-blue-500/20"
            :label="$t('common.save')"
            :loading="loading"
            />
        </div>
        </q-form>
        
        </div>
    </div>
</template>

<style scoped>
.card-premium {
  background-color: white;
  border-color: #e2e8f0;
}
:global(.dark) .card-premium {
  background-color: #1e293b;
  border-color: rgba(255, 255, 255, 0.05);
  border-radius: 1.5rem;
  border-width: 1px;
  box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}
.dark .card-premium {
  box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.3);
}

.premium-q-input :deep(.q-field__control) {
  border-radius: 12px;
}
.dark .premium-q-input :deep(.q-field__control) {
  background: #0f172a;
}
.dark .premium-q-input :deep(.q-field__native) {
  color: white;
}
.dark .premium-q-input :deep(.q-field__label) {
  color: #94a3b8;
}
</style>
