<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 bg-[#F8F9FA] dark:bg-[#020617] min-h-screen transition-colors duration-300">
    
    <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="text-slate-600 dark:text-white hover:bg-slate-100 dark:hover:bg-slate-800"
          @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 shadow-lg shadow-blue-500/20"
          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 pb-20">
      
      <!-- VIEW MODE: Premium Card with Banner -->
      <div v-if="!isEditing" class="bg-white dark:bg-[#1e293b] border border-slate-200 dark:border-slate-700/50 rounded-3xl shadow-xl dark:shadow-none overflow-hidden fade-in min-h-[500px] flex flex-col transition-colors duration-300">
        
        <!-- 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 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-[#1e293b] shadow-2xl rounded-[2.5rem] bg-white dark:bg-slate-800 transition-colors duration-300"
              />
            </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-slate-800/50 px-3 py-1.5 rounded-xl border border-slate-100 dark:border-slate-700">
                      <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-slate-800/50 px-3 py-1.5 rounded-xl border border-slate-100 dark:border-slate-700">
                      <q-icon name="verified_user" size="xs" :class="userData.emailVerifiedAt ? 'text-green-500' : 'text-amber-500'" />
                      <span class="text-sm">{{ userData.emailVerifiedAt ? $t('profile.emailVerified') : $t('profile.verifyEmail') }}</span>
                  </div>
              </div>
            </div>
          </div>
        </div>

        <!-- View Details Content -->
        <div class="p-8 md:p-12 flex-grow">
           <div class="max-w-3xl mx-auto h-full fade-in">
              <h3 class="text-sm font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest flex items-center gap-2 mb-8">
                 <span class="w-2 h-2 bg-blue-600 rounded-full"></span> {{ $t('profile.accountDetails') }}
              </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 dark:text-blue-400 group-hover:scale-110 transition-transform">
                       <q-icon name="smartphone" size="24px" />
                    </div>
                    <div>
                       <div class="text-[10px] font-black text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-0.5">{{ $t('profile.phone') }}</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 dark:text-indigo-400 group-hover:scale-110 transition-transform">
                       <q-icon name="calendar_today" size="24px" />
                    </div>
                    <div>
                       <div class="text-[10px] font-black text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-0.5">{{ $t('profile.joinedAt') }}</div>
                       <div class="text-lg font-bold text-slate-900 dark:text-white tracking-tight">{{ formatDate(userData.createdAt) }}</div>
                    </div>
                 </div>
              </div>
           </div>
        </div>
      </div>

      <!-- EDIT MODE: Tabs and Forms (Clean Layout) -->
      <div v-else class="fade-in">
          <!-- Tab Selector -->
          <div class="flex justify-center mb-8">
            <div class="bg-white dark:bg-[#1e293b] p-1.5 rounded-2xl flex items-center gap-1 border border-slate-200 dark:border-slate-700 shadow-sm">
                <button 
                  @click="activeTab = 'general'"
                  class="px-6 md:px-8 py-3 rounded-xl font-black text-xs uppercase tracking-widest transition-all flex items-center gap-2"
                  :class="activeTab === 'general' ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 shadow-sm scale-100' : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 scale-95 opacity-70'"
                >
                  <q-icon name="person_outline" size="18px" /> {{ $t('profile.generalInfo') }}
                </button>
                <button 
                  @click="activeTab = 'security'"
                  class="px-6 md:px-8 py-3 rounded-xl font-black text-xs uppercase tracking-widest transition-all flex items-center gap-2"
                  :class="activeTab === 'security' ? 'bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 shadow-sm scale-100' : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 scale-95 opacity-70'"
                >
                  <q-icon name="lock_open" size="18px" /> {{ $t('profile.security') }}
                </button>
            </div>
          </div>
          
          <!-- Edit Content -->
          <div class="max-w-3xl mx-auto">
              <div v-if="activeTab === 'general'" class="bg-white dark:bg-[#1e293b] border border-slate-200 dark:border-slate-700/50 rounded-3xl shadow-xl dark:shadow-none p-6 md:p-10">
                  <ProfileEditForm
                      v-model="userData"
                      :loading="isProfileSaving"
                      :verifying="isSendingVerify"
                      @submit="handleUpdateProfile"
                      @upload="handleFileUpload"
                      @verify="handleSendVerifyEmail"
                  />
              </div>
              <div v-else class="bg-white dark:bg-[#1e293b] border border-slate-200 dark:border-slate-700/50 rounded-3xl shadow-xl dark:shadow-none p-6 md:p-10">
                  <PasswordChangeForm
                      v-model="passwordForm"
                      :loading="isPasswordSaving"
                      @submit="handleUpdatePassword"
                  />
              </div>
          </div>
      </div>
      
    </div>

  </div>
</template>

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

/* Removed card-premium and dark mode overrides as we used utility classes */

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

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