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

// User Profile Data Management
const userData = ref({
  firstName: currentUser.value?.firstName || '',
  lastName: currentUser.value?.lastName || '',
  email: currentUser.value?.email || '',
  phone: '0812345678',
  joinDate: '12 ธ.ค. 2024',
  photoURL: '', 
  prefix: 'นาย' 
})

// 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 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 (Mock Implementation)
const saveProfile = () => {
  // Combine data for validation
  const formData = {
    ...userData.value,
    ...passwordForm
  }

  if (!validate(formData, validationRules)) return

  currentUser.value.firstName = userData.value.firstName
  currentUser.value.lastName = userData.value.lastName
  currentUser.value.email = userData.value.email
  
  // Successful save
  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">โปรไฟล์ของฉัน</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>
          แก้ไขโปรไฟล์
        </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">อีเมล</span>
            <p class="value">{{ userData.email }}</p>
          </div>
          <div class="info-group">
            <span class="label">เบอร์โทรศัพท์</span>
            <p class="value">{{ userData.phone }}</p>
          </div>
          <div class="info-group">
            <span class="label">สมัครสมาชิกเมื่อ</span>
            <p class="value">{{ userData.joinDate }}</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">แก้ไขข้อมูลส่วนตัว</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">รูปโปรไฟล์ของคุณ</h3>
          <p class="text-xs text-slate-500 mb-4 uppercase tracking-widest font-bold">เฉพาะไฟล์ png , jpg</p>
          <button class="btn-upload" @click="triggerUpload">อัปโหลดรูปใหม่</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">คำนำหน้า</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">ชื่อ</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">นามสกุล</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">อีเมล</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">เบอร์โทรศัพท์</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">ความปลอดภัย</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">รหัสผ่านปัจจุบัน</label>
            <input type="password" class="premium-input w-full" placeholder="••••••••">
          </div>
          <div class="space-y-2">
            <label class="text-xs font-black uppercase tracking-widest text-slate-500 dark:text-slate-300">รหัสผ่านใหม่</label>
            <input 
              v-model="passwordForm.newPassword"
              type="password" 
              class="premium-input w-full"
              :class="{ '!border-red-500': errors.newPassword }"
              @input="clearFieldError('newPassword')"
            >
             <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">ยืนยันรหัสผ่านใหม่</label>
            <input 
              v-model="passwordForm.confirmPassword"
              type="password" 
              class="premium-input w-full"
              :class="{ '!border-red-500': errors.confirmPassword }"
              @input="clearFieldError('confirmPassword')"
            >
            <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">บันทึกข้อมูล</button>
        <button class="btn-cancel-premium md:w-32" @click="toggleEdit(false)">ยกเลิก</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>
