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

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

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



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

// Certificates State
const certificates = ref<any[]>([])
const isLoadingCerts = 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
})

// ...


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 or profile update)
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 loadCertificates = async () => {
  isLoadingCerts.value = true
  const res = await fetchAllCertificates()
  if (res.success) {
    certificates.value = res.data || []
  }
  isLoadingCerts.value = false
}

const viewCertificate = (url: string) => {
  if (url) {
    window.open(url, '_blank')
  }
}

onMounted(async () => {
  await fetchUserProfile(true)
  loadCertificates()
  isHydrated.value = true
})
</script>

<template>
  <div class="page-container">
    
    <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>

      <!-- Section: My Certificates -->
      <div v-if="!isEditing && certificates.length > 0" class="mt-12 fade-in" style="animation-delay: 0.1s;">
         <h2 class="text-2xl font-black mb-6 text-slate-900 dark:text-white flex items-center gap-3">
           <q-icon name="workspace_premium" color="warning" size="32px" />
           ประกาศนียบัตรของฉัน
         </h2>
         <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="cert in certificates" :key="cert.certificate_id" class="card-premium p-6 hover:border-warning/50 transition-all group">
               <div class="flex items-start justify-between mb-4">
                  <div class="p-3 rounded-xl bg-orange-50 dark:bg-orange-900/10 text-orange-600 dark:text-orange-400">
                     <q-icon name="card_membership" size="32px" />
                  </div>
                  <q-btn flat round color="primary" icon="download" @click="viewCertificate(cert.download_url)" class="opacity-0 group-hover:opacity-100 transition-opacity" />
               </div>
               <h3 class="font-bold text-slate-900 dark:text-white mb-1 line-clamp-1">{{ getLocalizedText(cert.course_title) }}</h3>
               <p class="text-xs text-slate-500 dark:text-slate-400 mb-4 italic">ออกเมื่อ: {{ formatDate(cert.issued_at) }}</p>
               <q-btn 
                 unelevated 
                 rounded 
                 color="warning" 
                 text-color="dark" 
                 class="w-full font-bold" 
                 label="ดูประกาศนียบัตร" 
                 @click="viewCertificate(cert.download_url)" 
               />
            </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 {
  background-color: white;
  border-color: #e2e8f0;
  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 {
  background-color: #1e293b;
  border-color: rgba(255, 255, 255, 0.05);
  box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.3);
}

.info-group .label {
  font-size: 0.75rem;
  font-weight: 900;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  color: #64748b;
  display: block;
  margin-bottom: 0.5rem;
}

.dark .info-group .label {
  color: #94a3b8;
}

.info-group .value {
  font-size: 1.125rem;
  font-weight: 700;
  color: #0f172a;
}

.dark .info-group .value {
  color: 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>
