<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCouponStore } from '@/stores/coupon'
import { authService } from '@/services/authService'
import { getImageUrl } from '@/utils/imageUrl'
import { useI18n } from 'vue-i18n'

const router = useRouter()
const { t } = useI18n()
const couponStore = useCouponStore()

const userName = ref(localStorage.getItem('user_name') || t('profile.user'))
const userEmail = ref(localStorage.getItem('user_email') || '')
const userRole = ref(localStorage.getItem('user_role') || 'PASSENGER')
const userPhoto = ref(localStorage.getItem('profile_photo_url') || '')
const autoLocation = ref(false)

const showQRModal = ref(false)
const showEditModal = ref(false)
const isUpdating = ref(false)
const selectedCode = ref('')
const selectedTitle = ref('')

// Edit Form
const editForm = ref({
  full_name: userName.value,
  password: '',
  profile_photo: null as File | null,
  auto_location: autoLocation.value
})
const photoPreview = ref(userPhoto.value)

onMounted(async () => {
  await couponStore.loadMyCoupons()
  // Refresh user data from server to be sure
  try {
    const freshUser = await authService.getCurrentUser()
    userName.value = freshUser.full_name
    userEmail.value = freshUser.email
    userRole.value = freshUser.role
    userPhoto.value = freshUser.profile_photo_url || ''
    autoLocation.value = freshUser.auto_location || false
    
    editForm.value.full_name = freshUser.full_name
    editForm.value.auto_location = freshUser.auto_location || false

    localStorage.setItem('user_name', freshUser.full_name)
    localStorage.setItem('profile_photo_url', freshUser.profile_photo_url || '')
    photoPreview.value = userPhoto.value
  } catch (e) {
    console.error('Failed to refresh user data', e)
  }
})

function handleLogout() {
  authService.logout()
  router.push('/login')
}

function showQR(code: string, title: string) {
  selectedCode.value = code
  selectedTitle.value = title
  showQRModal.value = true
}

function handlePhotoChange(e: Event) {
  const target = e.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    editForm.value.profile_photo = file
    photoPreview.value = URL.createObjectURL(file)
  }
}

async function handleUpdateProfile() {
  isUpdating.value = true
  try {
    const formData = new FormData()
    formData.append('full_name', editForm.value.full_name)
    formData.append('auto_location', String(editForm.value.auto_location))
    
    if (editForm.value.password) {
      formData.append('password', editForm.value.password)
    }
    if (editForm.value.profile_photo) {
      formData.append('profile_photo', editForm.value.profile_photo)
    }

    const updatedUser = await authService.updateMe(formData)
    
    // Update local state
    userName.value = updatedUser.full_name
    userPhoto.value = updatedUser.profile_photo_url || ''
    autoLocation.value = updatedUser.auto_location
    
    // Update localStorage
    localStorage.setItem('user_name', updatedUser.full_name)
    localStorage.setItem('profile_photo_url', updatedUser.profile_photo_url || '')
    
    showEditModal.value = false
    editForm.value.password = ''
    alert(t('profile.updateSuccess'))
  } catch (e: any) {
    alert(t('profile.updateError') + ' ' + (e.response?.data?.detail || e.message))
  } finally {
    isUpdating.value = false
  }
}

function getStatusLabel(status: string) {
  switch (status) {
    case 'claimed': return t('profile.pending')
    case 'redeemed': return t('profile.redeemed')
    case 'expired': return t('profile.expired')
    default: return status
  }
}

const getFullUrl = (path: string) => getImageUrl(path)
</script>

<template>
  <div class="profile-view">
    <header class="profile-header">
      <div class="profile-info-card">
        <div class="avatar-container">
          <div v-if="userPhoto" class="avatar-img" :style="{ backgroundImage: `url(${getFullUrl(userPhoto)})` }"></div>
          <div v-else class="avatar-placeholder">
            <span class="material-icons">person</span>
          </div>
          <button class="edit-badge" @click="showEditModal = true">
            <span class="material-icons">edit</span>
          </button>
        </div>
        
        <div class="info">
          <h1>{{ userName }}</h1>
          <p>{{ userEmail }}</p>
          <div class="badge-row">
            <span class="role-badge">{{ userRole }}</span>
            <span v-if="autoLocation" class="smart-badge">
              <span class="material-icons">gps_fixed</span>
              Smart Location
            </span>
          </div>
        </div>
        
        <div class="header-actions">
           <button class="logout-icon-btn" @click="handleLogout" :title="t('profile.logoutTitle')">
            <span class="material-icons">logout</span>
          </button>
        </div>
      </div>
    </header>

    <section class="my-coupons-section">
      <div class="section-header">
        <h2>{{ t('profile.myCoupons') }}</h2>
        <span class="count">{{ couponStore.myCoupons.length }}</span>
      </div>

      <div v-if="couponStore.myCoupons.length === 0" class="empty-coupons">
        <div class="empty-icon-circle">
          <span class="material-icons">confirmation_number</span>
        </div>
        <h3>{{ t('profile.emptyCoupons') }}</h3>
        <p>{{ t('profile.exploreOffers') }}</p>
        <button @click="router.push('/coupons')" class="btn-primary">{{ t('profile.viewOffers') }}</button>
      </div>

      <div v-else class="coupons-list">
        <div 
          v-for="userCoupon in couponStore.myCoupons" 
          :key="userCoupon.id" 
          :class="['user-coupon-card', userCoupon.status]"
        >
          <div class="coupon-main">
            <div class="coupon-details">
              <h3>{{ userCoupon.coupon?.title || t('coupons.title') }}</h3> // Reusing coupons.title for fallback
              <p class="biz-name">{{ userCoupon.coupon?.business?.name || t('coupons.restaurant') }}</p>
              <div class="code-row">
                <span class="code">{{ userCoupon.redemption_code }}</span>
                <span :class="['status-tag', userCoupon.status]">{{ getStatusLabel(userCoupon.status) }}</span>
              </div>
            </div>
            <button 
              v-if="userCoupon.status === 'claimed'" 
              class="btn-use"
              @click="showQR(userCoupon.redemption_code, userCoupon.coupon?.title || '')"
            >
              <span class="material-icons">qr_code_2</span>
              {{ t('profile.viewCode') }}
            </button>
          </div>
          <div class="coupon-footer">
             <span v-if="userCoupon.status === 'redeemed'">{{ t('profile.usedAt') }} {{ new Date(userCoupon.redeemed_at).toLocaleDateString() }}</span>
             <span v-else>{{ t('profile.claimedAt') }} {{ new Date(userCoupon.claimed_at).toLocaleDateString() }}</span>
          </div>
        </div>
      </div>
    </section>

    <!-- Edit Profile Modal -->
    <div v-if="showEditModal" class="modal-overlay" @click.self="showEditModal = false">
      <div class="edit-modal">
        <div class="modal-header">
          <h2>{{ t('profile.editProfile') }}</h2>
          <button class="close-btn" @click="showEditModal = false">
            <span class="material-icons">close</span>
          </button>
        </div>

        <form @submit.prevent="handleUpdateProfile" class="edit-form">
          <div class="photo-upload-section">
            <div class="photo-preview-container">
              <div v-if="photoPreview" class="preview-img" :style="{ backgroundImage: `url(${getFullUrl(photoPreview)})` }"></div>
              <div v-else class="preview-placeholder">
                <span class="material-icons">person</span>
              </div>
              <label for="photo-input" class="photo-label">
                <span class="material-icons">photo_camera</span>
              </label>
            </div>
            <input id="photo-input" type="file" @change="handlePhotoChange" accept="image/*" hidden>
            <p class="upload-hint">{{ t('profile.photoOptional') }}</p>
          </div>

          <div class="form-group">
            <label>{{ t('profile.nameLabel') }}</label>
            <input v-model="editForm.full_name" type="text" :placeholder="t('profile.namePlaceholder')" required>
          </div>

          <div class="form-group">
            <label>{{ t('profile.passwordOptional') }}</label>
            <input v-model="editForm.password" type="password" :placeholder="t('profile.passwordPlaceholder')">
            <p class="field-hint">{{ t('profile.passwordHint') }}</p>
          </div>

          <div class="form-group flex-row" style="margin-top: 1rem;">
            <label class="custom-checkbox">
              <input type="checkbox" v-model="editForm.auto_location" />
              <span class="checkmark"></span>
              <span class="cb-text">{{ t('auth.smartLocation') }}</span>
            </label>
          </div>

          <div class="modal-actions">
            <button type="button" class="btn-cancel" @click="showEditModal = false">{{ t('profile.cancel') }}</button>
            <button type="submit" class="btn-save" :disabled="isUpdating">
              <span v-if="isUpdating" class="material-icons spin">refresh</span>
              {{ isUpdating ? t('profile.saving') : t('profile.save') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- QR Modal -->
    <div v-if="showQRModal" class="modal-overlay" @click.self="showQRModal = false">
      <div class="qr-modal">
        <button class="close-modal" @click="showQRModal = false">
          <span class="material-icons">close</span>
        </button>
        <div class="qr-header">
           <span class="material-icons">verified</span>
           <h3>{{ t('profile.qrTitle') }}</h3>
        </div>
        <p class="promo-title">{{ selectedTitle }}</p>
        
        <div class="qr-content">
           <div class="qr-placeholder">
             <span class="material-icons">qr_code_2</span>
           </div>
           <div class="redemption-box">
             <p>{{ t('profile.qrCode') }}</p>
             <code class="big-code">{{ selectedCode }}</code>
           </div>
        </div>
        
        <p class="qr-instructions">{{ t('profile.qrInstructions') }}</p>
        
        <button class="btn-done" @click="showQRModal = false">{{ t('profile.understood') }}</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.profile-view {
  padding: 1.5rem;
  background: var(--bg-primary);
  min-height: 100%;
}

.profile-header {
  margin-bottom: 2rem;
}

.profile-info-card {
  background: var(--card-bg);
  border-radius: 28px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1.5rem;
  box-shadow: 0 10px 30px var(--shadow);
  border: 1px solid var(--border-color);
  position: relative;
  overflow: hidden;
}

.avatar-container {
  position: relative;
}

.avatar-img, .avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 24px;
  background-size: cover;
  background-position: center;
  border: 3px solid var(--header-bg);
}

.avatar-placeholder {
  background: var(--bg-secondary);
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-placeholder .material-icons {
  font-size: 3rem;
}

.edit-badge {
  position: absolute;
  bottom: -5px;
  right: -5px;
  background: var(--text-primary);
  color: var(--bg-primary);
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.edit-badge .material-icons { font-size: 1rem; }

.info h1 { font-size: 1.4rem; margin-bottom: 2px; }
.info p { color: var(--text-secondary); font-size: 0.9rem; margin-bottom: 8px; }

.role-badge {
  background: var(--active-bg);
  color: var(--active-color);
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 700;
  text-transform: uppercase;
}

.header-actions {
  margin-left: auto;
}

.logout-icon-btn {
  background: #ffebf0;
  color: #d32f2f;
  border: none;
  border-radius: 12px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.logout-icon-btn:hover { background: #d32f2f; color: white; }

.section-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.section-header h2 { font-size: 1.25rem; }

.section-header .count {
  background: var(--text-primary);
  color: var(--bg-primary);
  padding: 2px 10px;
  border-radius: 20px;
  font-weight: 800;
  font-size: 0.8rem;
}

.empty-coupons {
  padding: 4rem 2rem;
  text-align: center;
  background: var(--card-bg);
  border-radius: 24px;
  border: 2px dashed var(--border-color);
}

.empty-icon-circle {
  width: 70px;
  height: 70px;
  background: var(--bg-secondary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 1.5rem;
  color: var(--text-secondary);
}

.empty-icon-circle .material-icons { font-size: 2.5rem; }

.btn-primary {
  margin-top: 1.5rem;
  background: var(--text-primary);
  color: var(--bg-primary);
  border: none;
  padding: 12px 24px;
  border-radius: 16px;
  font-weight: 700;
  cursor: pointer;
}

.coupons-list {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
}

.user-coupon-card {
  background: var(--card-bg);
  border-radius: 20px;
  border: 1px solid var(--border-color);
  overflow: hidden;
  box-shadow: 0 4px 15px var(--shadow);
  transition: transform 0.2s;
}

.user-coupon-card:hover { transform: scale(1.02); }

.coupon-main {
  padding: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-details h3 { font-size: 1.1rem; margin-bottom: 4px; }
.biz-name { font-size: 0.9rem; color: var(--active-color); font-weight: 700; }

.code-row {
  margin-top: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.code {
  font-family: 'Courier New', Courier, monospace;
  background: var(--bg-secondary);
  padding: 6px 12px;
  border-radius: 8px;
  font-weight: 800;
  font-size: 1rem;
  border: 1px dashed var(--border-color);
}

.status-tag {
  font-size: 0.7rem;
  padding: 4px 10px;
  border-radius: 8px;
  font-weight: 800;
  text-transform: uppercase;
}

.status-tag.claimed { background: #e3f2fd; color: #1976d2; }
.status-tag.redeemed { background: #e8f5e9; color: #2e7d32; opacity: 0.7; }

.btn-use {
  background: var(--header-bg);
  color: var(--header-text);
  border: none;
  padding: 12px 18px;
  border-radius: 14px;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.coupon-footer {
  padding: 10px 1.5rem;
  background: var(--bg-secondary);
  font-size: 0.8rem;
  color: var(--text-secondary);
  border-top: 1px solid var(--border-color);
  font-weight: 600;
}

/* Modal Base */
.modal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.7);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  padding: 1.5rem;
}

/* Edit Modal */
.edit-modal {
  background: var(--card-bg);
  width: 100%;
  max-width: 450px;
  border-radius: 32px;
  padding: 2rem;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.close-btn, .close-modal {
  background: var(--bg-secondary);
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.photo-upload-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 2rem;
}

.photo-preview-container {
  position: relative;
  margin-bottom: 1rem;
}

.preview-img, .preview-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 30px;
  background-size: cover;
  background-position: center;
  border: 4px solid var(--header-bg);
}

.preview-placeholder {
  background: var(--bg-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-placeholder .material-icons { font-size: 4rem; color: var(--text-secondary); }

.photo-label {
  position: absolute;
  bottom: -5px;
  right: -5px;
  background: var(--active-color);
  color: white;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0,0,0,0.3);
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  font-size: 0.85rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  color: var(--text-secondary);
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border-radius: 14px;
  border: 1px solid var(--border-color);
  background: var(--bg-primary);
  color: var(--text-primary);
  font-size: 1rem;
}

.field-hint, .upload-hint {
  font-size: 0.75rem;
  color: var(--text-secondary);
  margin-top: 4px;
}

.btn-save {
  flex: 2;
  background: var(--text-primary);
  color: var(--bg-primary);
  border: none;
  padding: 14px;
  border-radius: 16px;
  font-weight: 700;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-cancel {
  flex: 1;
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: none;
  padding: 14px;
  border-radius: 16px;
  font-weight: 700;
  cursor: pointer;
}

/* Modal Actions */
.modal-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

/* QR Modal Enhanced */
.qr-modal {
  background: var(--card-bg);
  width: 100%;
  max-width: 400px;
  border-radius: 40px;
  padding: 2.5rem;
  text-align: center;
  position: relative;
}

.qr-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-bottom: 1rem;
}

.qr-header .material-icons { color: #4caf50; font-size: 3rem; }
.qr-header h3 { font-size: 1.5rem; }

.promo-title {
  color: var(--active-color);
  font-weight: 800;
  margin-bottom: 2rem;
  font-size: 1.1rem;
}

.qr-content {
  background: #f8f9fa;
  padding: 2rem;
  border-radius: 30px;
  margin-bottom: 2rem;
  border: 1px solid #eee;
}

.qr-placeholder {
  width: 120px;
  height: 120px;
  background: white;
  margin: 0 auto 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
}

.qr-placeholder .material-icons { font-size: 6rem; color: #222; }

.redemption-box p { font-size: 0.7rem; font-weight: 800; color: #888; letter-spacing: 1px; margin-bottom: 4px; }

.big-code {
  font-size: 1.8rem;
  font-weight: 900;
  color: #111;
  letter-spacing: 3px;
}

.qr-instructions {
  font-size: 0.9rem;
  line-height: 1.4;
  color: var(--text-secondary);
  margin-bottom: 2rem;
}

.btn-done {
  width: 100%;
  padding: 16px;
  border-radius: 20px;
  background: var(--text-primary);
  color: var(--bg-primary);
  border: none;
  font-weight: 800;
  cursor: pointer;
}

.spin { animation: spin 1s linear infinite; }
@keyframes spin { 100% { transform: rotate(360deg); } }

.badge-row {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 8px;
}

.smart-badge {
  background: rgba(0, 212, 255, 0.1);
  color: #00d4ff;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 0.7rem;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 4px;
  border: 1px solid rgba(0, 212, 255, 0.2);
}

.smart-badge .material-icons { font-size: 0.9rem; }

/* Custom Checkbox inside Modal */
.custom-checkbox {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  cursor: pointer;
}

.custom-checkbox input { display: none; }

.checkmark {
  width: 1.25rem;
  height: 1.25rem;
  background: var(--bg-secondary);
  border: 1.5px solid var(--border-color);
  border-radius: 6px;
  position: relative;
  transition: all 0.2s;
}

.custom-checkbox input:checked + .checkmark {
  background: var(--active-color);
  border-color: var(--active-color);
}

.checkmark:after {
  content: "";
  position: absolute;
  left: 6px; top: 2px;
  width: 5px; height: 10px;
  border: solid #000;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  display: none;
}

.custom-checkbox input:checked + .checkmark:after { display: block; }

.cb-text {
  font-size: 0.85rem;
  color: var(--text-secondary);
  font-weight: 600;
}
</style>
