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

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

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



const isEditing = ref(false)
const activeTab = ref<'general' | 'security'>('general')
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(locale.value === 'th' ? 'th-TH' : 'en-US', { 
      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: 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.createdAt = newUser.createdAt || ''
    userData.value.emailVerifiedAt = newUser.emailVerifiedAt
  }
}, { deep: true })



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

<template>
  <div class="page-container">
    
    <div class="flex items-center justify-between mb-8">
      <div class="flex items-center gap-4">
        <q-btn
          v-if="isHydrated && isEditing"
          flat
          round
          icon="arrow_back"
          class="dark:text-white"
          @click="toggleEdit(false)"
        />
        <div class="flex items-start gap-4">
          <span class="w-1.5 h-10 md:h-12 bg-blue-600 rounded-full shadow-lg shadow-blue-500/50 mt-1 flex-shrink-0"></span>
          <div>
            <h1 class="text-3xl md:text-4xl font-black text-slate-900 dark:text-white leading-tight">
              {{ (isHydrated && isEditing) ? $t('profile.editProfile') : $t('profile.myProfile') }}
            </h1>
          </div>
        </div>
      </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 class="max-w-4xl mx-auto">
      <!-- Unified Premium Container -->
      <div class="card-premium overflow-hidden fade-in min-h-[600px] flex flex-col">
        
        <!-- Part 1: Identity Header (Banner & Avatar) -->
        <div class="relative">
          <div class="h-40 bg-gradient-to-r from-blue-700 via-blue-600 to-indigo-700 relative overflow-hidden">
             <!-- Abstract Patterns -->
             <div class="absolute inset-0 opacity-10">
                <div class="absolute -top-10 -right-10 w-64 h-64 rounded-full bg-white blur-3xl"></div>
                <div class="absolute -bottom-10 -left-10 w-48 h-48 rounded-full bg-indigo-300 blur-3xl"></div>
             </div>
          </div>
          
          <div class="px-8 md:px-12 flex flex-col md:flex-row items-center md:items-end gap-8 md:gap-12 -mt-12 pb-8 border-b border-slate-100 dark:border-white/5 relative z-10">
            <div class="relative group flex-shrink-0">
              <UserAvatar 
                :photo-u-r-l="userData.photoURL" 
                :first-name="userData.firstName" 
                :last-name="userData.lastName" 
                size="140"
                class="border-[6px] border-white dark:border-slate-800 shadow-2xl rounded-[2.5rem] bg-white dark:bg-slate-900"
              />
            </div>
            
            <div class="text-center md:text-left pt-4 md:pt-0 flex-grow min-w-0">
              <h2 class="text-3xl md:text-4xl font-black text-slate-900 dark:text-white mb-2 leading-tight tracking-tight break-words">
                {{ userData.firstName }} {{ userData.lastName }}
              </h2>
              <div class="flex flex-wrap items-center justify-center md:justify-start gap-4">
                  <div class="flex items-center gap-2 text-slate-500 dark:text-slate-400 font-bold bg-slate-50 dark:bg-white/5 px-3 py-1.5 rounded-xl border border-slate-100 dark:border-white/5">
                      <q-icon name="alternate_email" size="xs" class="text-blue-500" />
                      <span class="text-sm">{{ userData.email }}</span>
                  </div>
                  <div class="flex items-center gap-2 text-slate-500 dark:text-slate-400 font-bold bg-slate-50 dark:bg-white/5 px-3 py-1.5 rounded-xl border border-slate-100 dark:border-white/5">
                      <q-icon name="verified_user" size="xs" :class="userData.emailVerifiedAt ? 'text-green-500' : 'text-amber-500'" />
                      <span class="text-sm">{{ userData.emailVerifiedAt ? 'ยืนยันแล้ว' : 'รอการยืนยัน' }}</span>
                  </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Part 2: Interactive Controls & Content -->
        <div class="p-8 md:p-12 flex-grow">
          
          <!-- Tab Selector (Segmented Pill) -->
          <div v-if="isEditing" class="flex justify-center mb-12">
            <div class="bg-slate-100 dark:bg-slate-800/50 p-1.5 rounded-2xl flex items-center gap-1 border border-slate-200 dark:border-white/5 shadow-inner">
                <button 
                  @click="activeTab = 'general'"
                  class="px-8 py-3 rounded-xl font-black text-xs uppercase tracking-widest transition-all flex items-center gap-2"
                  :class="activeTab === 'general' ? 'bg-white dark:bg-slate-700 text-blue-600 shadow-md scale-100' : 'text-slate-500 hover:text-slate-700 dark:hover:text-white scale-95 opacity-70'"
                >
                  <q-icon name="person_outline" size="18px" /> ข้อมูลทั่วไป
                </button>
                <button 
                  @click="activeTab = 'security'"
                  class="px-8 py-3 rounded-xl font-black text-xs uppercase tracking-widest transition-all flex items-center gap-2"
                  :class="activeTab === 'security' ? 'bg-white dark:bg-slate-700 text-amber-600 shadow-md scale-100' : 'text-slate-500 hover:text-slate-700 dark:hover:text-white scale-95 opacity-70'"
                >
                  <q-icon name="lock_open" size="18px" /> ความปลอดภัย
                </button>
            </div>
          </div>

          <!-- Content Switching -->
          <div class="max-w-3xl mx-auto h-full">
            <template v-if="!isEditing">
               <div class="fade-in">
                  <h3 class="text-sm font-black text-slate-400 uppercase tracking-widest flex items-center gap-2 mb-8">
                     <span class="w-2 h-2 bg-blue-600 rounded-full"></span> รายละเอียดบัญชี
                  </h3>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-8">
                     <div class="flex items-center gap-4 group">
                        <div class="w-12 h-12 rounded-2xl bg-blue-50 dark:bg-blue-900/20 flex items-center justify-center text-blue-600 group-hover:scale-110 transition-transform">
                           <q-icon name="smartphone" size="24px" />
                        </div>
                        <div>
                           <div class="text-[10px] font-black text-slate-400 uppercase tracking-wider mb-0.5">เบอร์โทรศัพท์</div>
                           <div class="text-lg font-bold text-slate-900 dark:text-white tracking-tight">{{ userData.phone || '-' }}</div>
                        </div>
                     </div>
                     <div class="flex items-center gap-4 group">
                        <div class="w-12 h-12 rounded-2xl bg-indigo-50 dark:bg-indigo-900/20 flex items-center justify-center text-indigo-600 group-hover:scale-110 transition-transform">
                           <q-icon name="calendar_today" size="24px" />
                        </div>
                        <div>
                           <div class="text-[10px] font-black text-slate-400 uppercase tracking-wider mb-0.5">วันที่เริ่มเป็นสมาชิก</div>
                           <div class="text-lg font-bold text-slate-900 dark:text-white tracking-tight">{{ formatDate(userData.createdAt) }}</div>
                        </div>
                     </div>
                  </div>
               </div>
            </template>

            <template v-else>
               <div class="fade-in">
                  <div v-if="activeTab === 'general'">
                      <ProfileEditForm
                          v-model="userData"
                          :loading="isProfileSaving"
                          :verifying="isSendingVerify"
                          @submit="handleUpdateProfile"
                          @upload="handleFileUpload"
                          @verify="handleSendVerifyEmail"
                          flat
                      />
                  </div>
                  <div v-else>
                      <PasswordChangeForm
                          v-model="passwordForm"
                          :loading="isPasswordSaving"
                          @submit="handleUpdatePassword"
                          flat
                      />
                  </div>
               </div>
            </template>
          </div>
        </div>
      </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>
