<script setup lang="ts">
/**
 * @file profile.vue
 * @description User Profile & Settings Page.
 * Allows users to view their profile details and toggle an edit mode to update information.
 * Features a premium design with glassmorphism and gradient effects.
 */

definePageMeta({
  layout: 'default',
  middleware: 'auth'
})

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

const { currentUser } = useAuth()
const { errors, validate, clearFieldError } = useFormValidation()
const isEditing = 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
  }
}

// User Profile Data Management
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 || '' 
})

// Password Form (Separate from userData for security/logic)
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// Validation Rules
const validationRules = {
  firstName: { rules: { required: true }, label: 'ชื่อ' },
  lastName: { rules: { required: true }, label: 'นามสกุล' },
  email: { rules: { required: true, email: true }, label: 'อีเมล' },
  phone: { rules: { required: true, pattern: /^0[0-9]{8,9}$/ }, label: 'เบอร์โทรศัพท์' },
  newPassword: { rules: { minLength: 6 }, label: 'รหัสผ่านใหม่' },
  confirmPassword: { rules: { match: 'newPassword' }, label: 'ยืนยันรหัสผ่าน' }
}

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
  // Clear errors when toggling modes
  if(edit === false) {
      // Logic to reset form if canceling could go here
  }
}

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

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

// Save Profile Updates
const saveProfile = async () => {
  // Combine data for validation
  const formData = {
    ...userData.value,
    ...passwordForm
  }

  // TODO: Add password validation if changing password is implemented via this API or handle separately
  // For now focused on profile fields

  const prefixMap: Record<string, string> = {
    'นาย': 'Mr.',
    'นาง': 'Mrs.',
    'นางสาว': 'Ms.'
  }

  if (currentUser.value) {
      const { updateUserProfile, changePassword } = useAuth()
      
      const payload = {
        first_name: userData.value.firstName,
        last_name: userData.value.lastName,
        // email: userData.value.email, // Email should not be updated via this endpoint as it causes backend 500 error (not in UserProfile schema)
        phone: userData.value.phone,
        prefix: {
          th: userData.value.prefix,
          en: prefixMap[userData.value.prefix] || ''
        }
      }

      // 1. Update Profile
      const profileResult = await updateUserProfile(payload)
      if (!profileResult?.success) {
        alert(profileResult?.error || 'เกิดข้อผิดพลาดในการบันทึกข้อมูลส่วนตัว')
        return
      }

      // 2. Change Password (if filled)
      if (passwordForm.currentPassword && passwordForm.newPassword) {
         if (passwordForm.newPassword !== passwordForm.confirmPassword) {
            alert('รหัสผ่านใหม่ไม่ตรงกัน')
            return
         }
         
         const passwordResult = await changePassword({
            oldPassword: passwordForm.currentPassword,
            newPassword: passwordForm.newPassword
         })

         if (!passwordResult.success) {
            alert(passwordResult.error || 'เปลี่ยนรหัสผ่านไม่สำเร็จ')
            // Don't return here, maybe we still want to show profile success? 
            // But usually we stop. Let's alert only.
         } else {
            // Clear password form on success
            passwordForm.currentPassword = ''
            passwordForm.newPassword = ''
            passwordForm.confirmPassword = ''
         }
      }

      alert('บันทึกข้อมูลเรียบร้อยแล้ว')
      isEditing.value = false
  }
}
</script>

<template>
  <div class="profile-page max-w-4xl mx-auto px-4 py-8">
    <!-- Header: Title and Edit action -->
    <div class="flex items-center justify-between mb-10">
      <h1 class="text-3xl font-black text-slate-900 dark:text-white">{{ $t('profile.myProfile') }}</h1>
      <div class="flex items-center gap-6">
        <button v-if="!isEditing" class="btn-premium-edit" @click="toggleEdit(true)">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
          </svg>
          {{ $t('profile.editProfile') }}
        </button>
      </div>
    </div>

    <!-- Profile View Card -->
    <!-- VIEW MODE: Display Profile Information -->
    <div v-if="!isEditing" class="card-premium overflow-hidden">
      <!-- Cover Banner -->
      <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>

          </div>
        </div>

        <!-- Info Grid -->
        <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.email') }}</span>
            <p class="value">{{ userData.email }}</p>
          </div>
          <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>

    <!-- Edit Profile Card -->
    <!-- EDIT MODE: Edit Profile Form -->
    <div v-else class="card-premium p-8 md:p-12">
      <div class="flex items-center gap-4 mb-10">
        <button class="p-2 hover:bg-white/5 rounded-xl transition-colors" @click="toggleEdit(false)">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
        </button>
        <h2 class="text-2xl font-black text-slate-900 dark:text-white">{{ $t('profile.editPersonalDesc') }}</h2>
      </div>
      
      <!-- Avatar Upload Section -->
      <div class="flex flex-col md:flex-row items-center gap-8 mb-12">
        <div class="relative group cursor-pointer" @click="triggerUpload">
          <UserAvatar 
            :photo-u-r-l="userData.photoURL" 
            :first-name="userData.firstName" 
            :last-name="userData.lastName" 
            size="112"
            class="rounded-3xl border-2 border-slate-200 dark:border-white/5 bg-slate-800 group-hover:opacity-50 transition-all"
          />
          <div class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </div>
          <input ref="fileInput" type="file" class="hidden" accept="image/*" @change="handleFileUpload" >
        </div>
        <div class="text-center md:text-left">
          <h3 class="font-black text-slate-900 dark:text-white mb-2">{{ $t('profile.yourAvatar') }}</h3>
          <p class="text-xs text-slate-500 mb-4 uppercase tracking-widest font-bold">{{ $t('profile.avatarHint') }}</p>
          <button class="btn-upload" @click="triggerUpload">{{ $t('profile.uploadNew') }}</button>
        </div>
      </div>

      <!-- Form Inputs -->
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
        <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.prefix') }}</label>
          <select v-model="userData.prefix" class="premium-input w-full">
            <option>นาย</option>
            <option>นาง</option>
            <option>นางสาว</option>
          </select>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.firstName') }}</label>
            <input 
              v-model="userData.firstName" 
              type="text" 
              class="premium-input w-full" 
              :class="{ '!border-red-500': errors.firstName }"
              @input="clearFieldError('firstName')"
            >
            <span v-if="errors.firstName" class="text-red-500 text-[10px] mt-1 font-bold">{{ errors.firstName }}</span>
          </div>
          <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.lastName') }}</label>
            <input 
              v-model="userData.lastName" 
              type="text" 
              class="premium-input w-full"
              :class="{ '!border-red-500': errors.lastName }"
              @input="clearFieldError('lastName')"
            >
            <span v-if="errors.lastName" class="text-red-500 text-[10px] mt-1 font-bold">{{ errors.lastName }}</span>
          </div>
        </div>
        <div class="space-y-2">
          <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.email') }}</label>
          <input 
            v-model="userData.email" 
            type="email" 
            class="premium-input w-full"
            :class="{ '!border-red-500': errors.email }"
            @input="clearFieldError('email')"
          >
          <span v-if="errors.email" class="text-red-500 text-[10px] mt-1 font-bold">{{ errors.email }}</span>
        </div>
        <div class="space-y-2">
          <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.phone') }}</label>
          <input 
            v-model="userData.phone" 
            type="text" 
            class="premium-input w-full"
            :class="{ '!border-red-500': errors.phone }"
            @input="clearFieldError('phone')"
          >
          <span v-if="errors.phone" class="text-red-500 text-[10px] mt-1 font-bold">{{ errors.phone }}</span>
        </div>
      </div>

      <!-- Security Section -->
      <div class="border-t border-slate-200 dark:border-white/5 pt-10 mb-10">
        <h3 class="text-lg font-black text-slate-900 dark:text-white mb-6">{{ $t('profile.security') }}</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.currentPassword') }}</label>
            <div class="relative">
              <input 
                v-model="passwordForm.currentPassword"
                :type="showCurrentPassword ? 'text' : 'password'"
                class="premium-input w-full pr-12" 
                placeholder="••••••••"
              >
              <button 
                type="button" 
                @click="showCurrentPassword = !showCurrentPassword"
                class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
                tabindex="-1"
              >
                <svg v-if="!showCurrentPassword" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                </svg>
              </button>
            </div>
          </div>
          <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.newPassword') }}</label>
            <div class="relative">
              <input 
                v-model="passwordForm.newPassword"
                :type="showNewPassword ? 'text' : 'password'"
                class="premium-input w-full pr-12"
                :class="{ '!border-red-500': errors.newPassword }"
                @input="clearFieldError('newPassword')"
              >
              <button 
                type="button" 
                @click="showNewPassword = !showNewPassword"
                class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
                tabindex="-1"
              >
                <svg v-if="!showNewPassword" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                </svg>
              </button>
            </div>
             <span v-if="errors.newPassword" class="text-red-500 text-[10px] mt-1 font-bold">{{ errors.newPassword }}</span>
          </div>
          <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">{{ $t('profile.confirmNewPassword') }}</label>
            <div class="relative">
              <input 
                v-model="passwordForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'" 
                class="premium-input w-full pr-12"
                :class="{ '!border-red-500': errors.confirmPassword }"
                @input="clearFieldError('confirmPassword')"
              >
              <button 
                type="button" 
                @click="showConfirmPassword = !showConfirmPassword"
                class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
                tabindex="-1"
              >
                <svg v-if="!showConfirmPassword" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                </svg>
              </button>
            </div>
            <span v-if="errors.confirmPassword" class="text-red-500 text-[10px] mt-1 font-bold">{{ errors.confirmPassword }}</span>
          </div>
        </div>
      </div>

      <!-- Actions -->
      <div class="flex flex-col md:flex-row gap-4 pt-6 border-t border-white/5">
        <button class="btn-save-premium flex-1" @click="saveProfile">{{ $t('common.save') }}</button>
        <button class="btn-cancel-premium md:w-32" @click="toggleEdit(false)">{{ $t('common.cancel') }}</button>
      </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: 2.5rem;
  border-width: 1px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.1);
}
.dark .card-premium {
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
}

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

.premium-input {
  @apply bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-white/10 rounded-2xl px-6 py-3.5 text-slate-900 dark:text-white focus:border-blue-500 outline-none transition-all placeholder:text-slate-400;
}

.btn-premium-edit {
  @apply flex items-center px-6 py-3 bg-blue-100 dark:bg-blue-600/10 text-blue-700 dark:text-blue-400 rounded-2xl text-sm font-black hover:bg-blue-600 hover:text-white transition-all border border-blue-300 dark:border-blue-500/20;
}

.btn-upload {
  @apply px-6 py-2.5 bg-blue-600 text-white rounded-xl text-xs font-black hover:bg-blue-500 transition-all shadow-lg shadow-blue-600/20;
}

.btn-save-premium {
  @apply bg-blue-600 text-white rounded-2xl py-4 font-black hover:bg-blue-500 transition-all shadow-lg dark:shadow-blue-600/20;
}

.btn-cancel-premium {
  @apply bg-slate-200 dark:bg-slate-700 text-slate-900 dark:text-white rounded-2xl py-4 font-black hover:bg-slate-300 dark:hover:bg-slate-600 transition-all;
}

@media (max-width: 768px) {
  .card-premium {
    @apply rounded-[2rem];
  }
}
</style>
