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

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

const { currentUser, updateUserProfile, changePassword, uploadAvatar, sendVerifyEmail, fetchUserProfile } = useAuth()
const { t } = useI18n()



const isEditing = ref(false)
const isProfileSaving = ref(false)
const isPasswordSaving = ref(false)
const isSendingVerify = 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 || '',
  emailVerifiedAt: currentUser.value?.emailVerifiedAt
})

// ...

// Watch for changes in global user state (e.g. after avatar upload)
watch(() => currentUser.value, (newUser) => {
  if (newUser) {
    userData.value.photoURL = newUser.photoURL || ''
    userData.value.firstName = newUser.firstName
    userData.value.lastName = newUser.lastName
    userData.value.prefix = newUser.prefix?.th || ''
    userData.value.email = newUser.email
    userData.value.phone = newUser.phone || ''
    userData.value.emailVerifiedAt = newUser.emailVerifiedAt
  }
}, { deep: true })

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


// Rules have been moved to components

const fileInput = ref<HTMLInputElement | null>(null) // Used in view mode (outside component)

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

// Updated to accept File object directly (or Event for view mode compatibility if needed)
const handleFileUpload = async (fileOrEvent: File | Event) => {
  let file: File | null = null

  if (fileOrEvent instanceof File) {
    file = fileOrEvent
  } else {
    // Fallback for native input change event
    const target = (fileOrEvent as Event).target as HTMLInputElement
    if (target.files && target.files[0]) {
      file = target.files[0]
    }
  }

  if (file) {
    // แสดงรูป Preview ก่อนอัปโหลด
    const reader = new FileReader()
    reader.onload = (e) => {
      userData.value.photoURL = e.target?.result as string
    }
    reader.readAsDataURL(file)

    // เรียกฟังก์ชัน uploadAvatar จาก useAuth
    isProfileSaving.value = true
    const result = await uploadAvatar(file)
    isProfileSaving.value = false

    if (result.success && result.data?.avatar_url) {
       userData.value.photoURL = result.data.avatar_url
    } else {
       console.error('Upload failed:', result.error)
       alert(result.error || t('profile.updateError'))
    }
  }
}

// Trigger upload for VIEW mode avatar click
const triggerUpload = () => {
    fileInput.value?.click()
}



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 handleSendVerifyEmail = async () => {
  isSendingVerify.value = true
  const result = await sendVerifyEmail()
  isSendingVerify.value = false
  
  if (result.success) {
    alert(result.message || t('profile.verifyEmailSuccess') || 'ส่งอีเมลยืนยันสำเร็จ')
  } else {
    if (result.code === 400) {
        alert(t('profile.emailAlreadyVerified') || 'อีเมลของคุณได้รับการยืนยันแล้ว')
    } else {
        alert(result.error || t('profile.verifyEmailError') || 'ส่งอีเมลไม่สำเร็จ')
    }
  }
}

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
}

// Watch for changes in global user state (e.g. after avatar upload)
watch(() => currentUser.value, (newUser) => {
  if (newUser) {
    userData.value.photoURL = newUser.photoURL || ''
    userData.value.firstName = newUser.firstName
    userData.value.lastName = newUser.lastName
    userData.value.prefix = newUser.prefix?.th || ''
    userData.value.email = newUser.email
    userData.value.phone = newUser.phone || ''
  }
}, { deep: true })

onMounted(async () => {
  await fetchUserProfile(true)
  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>
            <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">
        
        <ProfileEditForm
          v-model="userData"
          :loading="isProfileSaving"
          :verifying="isSendingVerify"
          @submit="handleUpdateProfile"
          @upload="handleFileUpload"
          @verify="handleSendVerifyEmail"
        />


        <PasswordChangeForm
          v-model="passwordForm"
          :loading="isPasswordSaving"
          @submit="handleUpdatePassword"
        />

      </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>
