<script setup lang="ts">
definePageMeta({
  layout: 'default',
  middleware: 'auth'
})

useHead({
  title: 'ตั้งค่าบัญชี - e-Learning'
})

const { currentUser, updateUserProfile, changePassword } = useAuth()
const { t } = useI18n()
const { errors, validate, clearFieldError } = useFormValidation()

const isEditing = ref(false)
const isProfileSaving = ref(false)
const isPasswordSaving = ref(false)
const isHydrated = ref(false)

const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return new Intl.DateTimeFormat('th-TH', { 
      day: 'numeric', 
      month: 'short', 
      year: 'numeric' 
    }).format(date)
  } catch (e) {
    return dateString
  }
}

const userData = ref({
  firstName: currentUser.value?.firstName || '',
  lastName: currentUser.value?.lastName || '',
  email: currentUser.value?.email || '',
  phone: currentUser.value?.phone || '',
  createdAt: formatDate(currentUser.value?.createdAt),
  photoURL: currentUser.value?.photoURL || '', 
  prefix: currentUser.value?.prefix?.th || '' 
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

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 passwordRules = [
  (val: string) => !!val || t('common.required'),
  (val: string) => val.length >= 6 || t('common.passwordTooShort')
]
const confirmPasswordRules = [
  (val: string) => !!val || t('common.required'),
  (val: string) => val === passwordForm.newPassword || t('common.passwordsDoNotMatch')
]

const showCurrentPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)

const fileInput = ref<HTMLInputElement | null>(null)

const toggleEdit = (edit: boolean) => {
  isEditing.value = edit
}

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

const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const reader = new FileReader()
    reader.onload = (e) => {
      userData.value.photoURL = e.target?.result as string
    }
    reader.readAsDataURL(target.files[0])
  }
}

const handleUpdateProfile = async () => {
  isProfileSaving.value = true
  
  const prefixMap: Record<string, string> = {
    'นาย': 'Mr.',
    'นาง': 'Mrs.',
    'นางสาว': 'Ms.'
  }

  const payload = {
    first_name: userData.value.firstName,
    last_name: userData.value.lastName,
    phone: userData.value.phone,
    prefix: {
      th: userData.value.prefix,
      en: prefixMap[userData.value.prefix] || ''
    }
  }

  const result = await updateUserProfile(payload)
  
  if (result?.success) {
    // success logic
  } else {
    alert(result?.error || t('profile.updateError'))
  }
  
  isProfileSaving.value = false
}

const handleUpdatePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    alert('รหัสผ่านใหม่ไม่ตรงกัน')
    return
  }
  
  isPasswordSaving.value = true
  
  const result = await changePassword({
    oldPassword: passwordForm.currentPassword,
    newPassword: passwordForm.newPassword
  })

  if (result.success) {
    alert(t('profile.passwordSuccess'))
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } else {
    alert(result.error || t('profile.passwordError'))
  }
  
  isPasswordSaving.value = false
}

onMounted(() => {
  isHydrated.value = true
})
</script>

<template>
  <div class="profile-page mx-auto px-4 py-8 max-w-4xl lg:max-w-5xl">
    
    <div class="flex items-center justify-between mb-8 md:mb-10">
      <div class="flex items-center gap-4">
        <q-btn
          v-if="isHydrated && isEditing"
          flat
          round
          icon="arrow_back"
          color="slate-700"
          class="dark:text-white"
          @click="toggleEdit(false)"
        />
        <h1 class="text-3xl font-black text-slate-900 dark:text-white">
          {{ (isHydrated && isEditing) ? $t('profile.editProfile') : $t('profile.myProfile') }}
        </h1>
      </div>

      <div class="min-h-9 flex items-center">
        <q-btn
          v-if="isHydrated && !isEditing"
          unelevated
          rounded
          color="primary"
          class="font-bold"
          icon="edit"
          :label="$t('profile.editProfile')"
          @click="toggleEdit(true)"
        />
        <div
          v-else-if="!isHydrated"
          class="h-9 w-24 rounded-md bg-slate-200 dark:bg-slate-700 animate-pulse"
        />
      </div>
    </div>

    <div v-if="!isHydrated" class="flex justify-center py-20">
       <q-spinner size="3rem" color="primary" />
    </div>

    <div v-else>
      <div v-if="!isEditing" class="card-premium overflow-hidden fade-in">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 h-32 w-full"/>
        <div class="px-8 pb-10 -mt-16">
          <div class="flex flex-col md:flex-row items-end gap-6 mb-10">
            <div class="relative flex-shrink-0">
              <UserAvatar 
                :photo-u-r-l="userData.photoURL" 
                :first-name="userData.firstName" 
                :last-name="userData.lastName" 
                size="128"
                class="border-4 border-white dark:border-[#1e293b] shadow-2xl bg-slate-800"
              />
              <div class="absolute bottom-2 right-2 bg-emerald-500 w-5 h-5 rounded-full border-4 border-white dark:border-[#1e293b]"/>
            </div>
            <div class="pb-2">
              <h2 class="text-3xl font-black text-slate-900 dark:text-white mb-1">{{ userData.firstName }} {{ userData.lastName }}</h2>
              <p class="text-slate-500 dark:text-slate-400 font-medium">{{ userData.email }}</p>
            </div>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            <div class="info-group">
              <span class="label">{{ $t('profile.phone') }}</span>
              <p class="value">{{ userData.phone || '-' }}</p>
            </div>
            <div class="info-group">
              <span class="label">{{ $t('profile.joinedAt') }}</span>
              <p class="value">{{ userData.createdAt }}</p>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-8 fade-in">
        
        <div class="card-premium p-8 h-fit">
          <h2 class="text-xl font-bold flex items-center gap-3 text-slate-900 dark:text-white mb-6">
            <q-icon name="person" class="text-blue-500 text-2xl" />
            {{ $t('profile.editPersonalDesc') }}
          </h2>

          <q-form @submit="handleUpdateProfile" 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="userData.photoURL" 
                  :first-name="userData.firstName" 
                  :last-name="userData.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>
                <input ref="fileInput" type="file" class="hidden" accept="image/*" @change="handleFileUpload" >
              </div>
              <div>
                <div class="font-bold text-slate-900 dark:text-white mb-1">{{ $t('profile.yourAvatar') }}</div>
                <q-btn 
                  flat 
                  dense 
                  no-caps 
                  color="primary" 
                  :label="$t('profile.uploadNew')" 
                  size="sm" 
                  @click="triggerUpload"
                />
              </div>
            </div>

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

            <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="userData.prefix"
                    :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="userData.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="userData.lastName"
                      outlined dense rounded
                      class="premium-q-input"
                      :rules="nameRules"
                      hide-bottom-space
                    />
                 </div>
               </div>

               <div>
                  <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.email') }}</label>
                  <q-input
                    v-model="userData.email"
                    type="email"
                    outlined dense rounded
                    class="premium-q-input"
                    :rules="emailRules"
                     hide-bottom-space
                     disable
                     :hint="$t('profile.emailHint')"
                   />
               </div>

               <div>
                  <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.phone') }}</label>
                  <q-input
                    v-model="userData.phone"
                    outlined dense rounded
                    class="premium-q-input"
                    :rules="phoneRules"
                    hide-bottom-space
                  />
               </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="isProfileSaving"
              />
            </div>
          </q-form>
        </div>


        <div class="card-premium p-8 h-fit">
          <h2 class="text-xl font-bold flex items-center gap-3 text-slate-900 dark:text-white mb-6">
            <q-icon name="lock" class="text-amber-500 text-2xl" />
            {{ $t('profile.security') }}
          </h2>
          
           <q-form @submit="handleUpdatePassword" class="flex flex-col gap-6">
              <div class="text-sm text-slate-500 dark:text-slate-400 mb-2">
                {{ $t('profile.securityDesc') }}
              </div>

             <div class="space-y-4">
                <div>
                  <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.currentPassword') }}</label>
                  <q-input
                    v-model="passwordForm.currentPassword"
                    :type="showCurrentPassword ? 'text' : 'password'"
                     outlined dense rounded
                     class="premium-q-input"
                     placeholder="••••••••"
                     :rules="[val => !!val || $t('common.required')]"
                   >
                    <template v-slot:append>
                      <q-icon
                        :name="showCurrentPassword ? 'visibility_off' : 'visibility'"
                        class="cursor-pointer text-slate-400"
                        @click="showCurrentPassword = !showCurrentPassword"
                      />
                    </template>
                  </q-input>
                </div>

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

                <div>
                  <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.newPassword') }}</label>
                  <q-input
                    v-model="passwordForm.newPassword"
                    :type="showNewPassword ? 'text' : 'password'"
                     outlined dense rounded
                     class="premium-q-input"
                     :placeholder="$t('profile.newPasswordHint')"
                     :rules="passwordRules"
                   >
                    <template v-slot:append>
                      <q-icon
                        :name="showNewPassword ? 'visibility_off' : 'visibility'"
                        class="cursor-pointer text-slate-400"
                        @click="showNewPassword = !showNewPassword"
                      />
                    </template>
                  </q-input>
                </div>

                <div>
                  <label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.confirmNewPassword') }}</label>
                  <q-input
                    v-model="passwordForm.confirmPassword"
                    :type="showConfirmPassword ? 'text' : 'password'"
                     outlined dense rounded
                     class="premium-q-input"
                     :placeholder="$t('profile.confirmPasswordHint')"
                     :rules="confirmPasswordRules"
                   >
                    <template v-slot:append>
                      <q-icon
                        :name="showConfirmPassword ? 'visibility_off' : 'visibility'"
                        class="cursor-pointer text-slate-400"
                        @click="showConfirmPassword = !showConfirmPassword"
                      />
                    </template>
                  </q-input>
                </div>
             </div>

             <div class="pt-2">
              <q-btn
                type="submit"
                 unelevated
                 rounded
                 class="w-full py-3 font-bold text-base shadow-lg shadow-amber-500/20"
                 style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white;"
                 :label="$t('profile.changePasswordBtn')"
                 :loading="isPasswordSaving"
               />
            </div>
          </q-form>
        </div>

      </div>
    </div>

  </div>
</template>

<style scoped>
.text-main {
  color: white;
}

.card-premium {
  @apply bg-white dark:bg-[#1e293b] border-slate-200 dark:border-white/5;
  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);
}

.info-group .label {
  @apply text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-400 block mb-2;
}
.info-group .value {
  @apply text-lg font-bold text-slate-900 dark:text-white;
}

.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;
}

.fade-in {
  animation: fadeIn 0.4s ease-out forwards;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
