<template>
  <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <h1 class="text-3xl font-bold text-gray-900 mb-8">Mon profil</h1>
    
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- Avatar Section -->
      <div class="lg:col-span-1">
        <div class="card p-6">
          <div class="text-center">
            <div class="relative inline-block">
              <img
                v-if="user?.avatar_url"
                :src="getMediaUrl(user.avatar_url)"
                :alt="user?.full_name"
                class="w-32 h-32 rounded-full object-cover border-4 border-white shadow-lg"
              >
              <div
                v-else
                class="w-32 h-32 rounded-full bg-primary-100 flex items-center justify-center border-4 border-white shadow-lg"
              >
                <User class="w-16 h-16 text-primary-600" />
              </div>
              
              <!-- Upload Button Overlay -->
              <button
                @click="$refs.avatarInput.click()"
                class="absolute bottom-0 right-0 bg-primary-600 text-white p-2 rounded-full shadow-lg hover:bg-primary-700 transition-colors"
                title="Changer l'avatar"
              >
                <Camera class="w-4 h-4" />
              </button>
            </div>
            
            <input
              ref="avatarInput"
              type="file"
              accept="image/*"
              class="hidden"
              @change="handleAvatarChange"
            >
            
            <h2 class="text-xl font-semibold text-gray-900 mt-4">{{ user?.full_name }}</h2>
            <p class="text-gray-600">@{{ user?.username }}</p>
            
            <div class="mt-4 text-sm text-gray-500">
              <p>Membre depuis {{ formatDate(user?.created_at) }}</p>
              <p>Taux de présence : {{ Math.round(user?.attendance_rate || 0) }}%</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Profile Form -->
      <div class="lg:col-span-2">
        <div class="card p-6">
          <h3 class="text-lg font-semibold text-gray-900 mb-6">Informations personnelles</h3>
          
          <form @submit.prevent="updateProfile" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="label">Nom complet</label>
                <input
                  v-model="form.full_name"
                  type="text"
                  required
                  class="input"
                  placeholder="Prénom Nom"
                >
              </div>
              
              <div>
                <label class="label">Nom d'utilisateur</label>
                <input
                  v-model="form.username"
                  type="text"
                  disabled
                  class="input bg-gray-50"
                  title="Le nom d'utilisateur ne peut pas être modifié"
                >
              </div>
            </div>
            
            <div>
              <label class="label">Email</label>
              <input
                v-model="form.email"
                type="email"
                disabled
                class="input bg-gray-50"
                title="L'email ne peut pas être modifié"
              >
            </div>
            
            <div>
              <label class="label">Bio</label>
              <textarea
                v-model="form.bio"
                rows="4"
                class="input"
                placeholder="Parlez-nous un peu de vous..."
                maxlength="500"
              />
              <p class="text-xs text-gray-500 mt-1">{{ (form.bio || '').length }}/500 caractères</p>
            </div>
            
            <div class="flex gap-3 pt-4">
              <button
                type="submit"
                :disabled="updating"
                class="btn-primary"
              >
                {{ updating ? 'Mise à jour...' : 'Mettre à jour' }}
              </button>
              <button
                type="button"
                @click="resetForm"
                class="btn-secondary"
              >
                Réinitialiser
              </button>
            </div>
          </form>
        </div>
        
        <!-- Stats Section -->
        <div class="card p-6 mt-6">
          <h3 class="text-lg font-semibold text-gray-900 mb-6">Mes statistiques</h3>
          
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="text-center p-4 bg-gray-50 rounded-lg">
              <div class="text-2xl font-bold text-primary-600">{{ stats.posts_count || 0 }}</div>
              <div class="text-sm text-gray-600">Publications</div>
            </div>
            
            <div class="text-center p-4 bg-gray-50 rounded-lg">
              <div class="text-2xl font-bold text-green-600">{{ stats.vlogs_count || 0 }}</div>
              <div class="text-sm text-gray-600">Vlogs</div>
            </div>
            
            <div class="text-center p-4 bg-gray-50 rounded-lg">
              <div class="text-2xl font-bold text-blue-600">{{ stats.albums_count || 0 }}</div>
              <div class="text-sm text-gray-600">Albums</div>
            </div>
            
            <div class="text-center p-4 bg-gray-50 rounded-lg">
              <div class="text-2xl font-bold text-purple-600">{{ stats.events_created || 0 }}</div>
              <div class="text-sm text-gray-600">Événements créés</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useToast } from 'vue-toastification'
import axios from '@/utils/axios'
import { getMediaUrl } from '@/utils/axios'
import { format } from 'date-fns'
import { fr } from 'date-fns/locale'
import { User, Camera } from 'lucide-vue-next'

const authStore = useAuthStore()
const toast = useToast()

const user = computed(() => authStore.user)
const updating = ref(false)
const stats = ref({})

const form = ref({
  full_name: '',
  username: '',
  email: '',
  bio: ''
})

function formatDate(date) {
  if (!date) return ''
  return format(new Date(date), 'MMMM yyyy', { locale: fr })
}

function resetForm() {
  form.value = {
    full_name: user.value?.full_name || '',
    username: user.value?.username || '',
    email: user.value?.email || '',
    bio: user.value?.bio || ''
  }
}

async function updateProfile() {
  updating.value = true
  try {
    const result = await authStore.updateProfile({
      full_name: form.value.full_name,
      bio: form.value.bio
    })
    
    if (result.success) {
      toast.success('Profil mis à jour avec succès')
    }
  } catch (error) {
    toast.error('Erreur lors de la mise à jour du profil')
  }
  updating.value = false
}

async function handleAvatarChange(event) {
  const file = event.target.files[0]
  if (!file) return
  
  // Validate file type
  if (!file.type.startsWith('image/')) {
    toast.error('Veuillez sélectionner une image')
    return
  }
  
  // Validate file size (max 5MB)
  if (file.size > 5 * 1024 * 1024) {
    toast.error('L\'image est trop volumineuse (max 5MB)')
    return
  }
  
  try {
    const result = await authStore.uploadAvatar(file)
    if (result.success) {
      toast.success('Avatar mis à jour avec succès')
    }
  } catch (error) {
    toast.error('Erreur lors de l\'upload de l\'avatar')
  }
  
  // Reset input
  event.target.value = ''
}

async function fetchUserStats() {
  try {
    const response = await axios.get(`/api/stats/user/${user.value.id}`)
    stats.value = response.data.content_stats
  } catch (error) {
    console.error('Error fetching user stats:', error)
  }
}

onMounted(() => {
  resetForm()
  fetchUserStats()
})
</script>
