<template>
  <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <!-- Loading state -->
      <div v-if="loading" class="text-center py-12">
        <LoadingLogo size="large" text="Chargement du profil..." />
      </div>

    <!-- Profile not found -->
    <div v-else-if="!profileUser" class="text-center py-12">
      <h1 class="text-2xl font-bold text-gray-900 mb-4">Profil non trouvé</h1>
      <p class="text-gray-600 mb-6">L'utilisateur que vous recherchez n'existe pas ou a été supprimé.</p>
      <router-link to="/" class="btn-primary">
        Retour à l'accueil
      </router-link>
    </div>

    <!-- Profile content -->
    <div v-else>
      <!-- Header -->
      <div class="mb-8">
        <div class="flex items-center justify-between mb-4">
          <router-link to="/" class="text-primary-600 hover:text-primary-700 flex items-center">
            <ArrowLeft class="w-4 h-4 mr-2" />
            Retour à l'accueil
          </router-link>
        </div>
        
        <!-- Profile Info -->
        <div class="card p-8 text-center">
          <!-- Avatar -->
          <div class="mb-6">
            <div class="relative inline-block">
              <img
                v-if="profileUser.avatar_url"
                :src="getMediaUrl(profileUser.avatar_url)"
                :alt="profileUser.full_name"
                class="w-32 h-32 rounded-full object-cover mx-auto border-4 border-white shadow-lg"
              >
              <div v-else class="w-32 h-32 rounded-full bg-primary-100 flex items-center justify-center mx-auto border-4 border-white shadow-lg">
                <User class="w-16 h-16 text-primary-600" />
              </div>
            </div>
          </div>
          
          <!-- User Info -->
          <h1 class="text-3xl font-bold text-gray-900 mb-2">{{ profileUser.full_name }}</h1>
          <p class="text-xl text-gray-600 mb-4">@{{ profileUser.username }}</p>
          
          <div v-if="profileUser.bio" class="text-gray-700 mb-6 max-w-2xl mx-auto">
            {{ profileUser.bio }}
          </div>
          
          <!-- Stats -->
          <div class="grid grid-cols-2 md:grid-cols-4 gap-6 mt-8">
            <div class="text-center">
              <div class="text-2xl font-bold text-primary-600">{{ userStats.posts_count || 0 }}</div>
              <div class="text-gray-600">Publications</div>
            </div>
            <div class="text-center">
              <div class="text-2xl font-bold text-success-600">{{ userStats.vlogs_count || 0 }}</div>
              <div class="text-gray-600">Vlogs</div>
            </div>
            <div class="text-center">
              <div class="text-2xl font-bold text-blue-600">{{ userStats.albums_count || 0 }}</div>
              <div class="text-gray-600">Albums</div>
            </div>
            <div class="text-center">
              <div class="text-2xl font-bold text-purple-600">{{ userStats.events_created || 0 }}</div>
              <div class="text-gray-600">Événements</div>
            </div>
          </div>
          
          <!-- Attendance Rate -->
          <div v-if="profileUser.attendance_rate !== undefined" class="mt-6">
            <div class="text-center">
              <div class="text-lg font-semibold text-gray-900 mb-2">Taux de présence</div>
              <div class="text-3xl font-bold text-success-600">{{ profileUser.attendance_rate.toFixed(1) }}%</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Recent Activity -->
      <div class="card p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Activité récente</h2>
        
        <div v-if="recentActivity.length === 0" class="text-center py-8 text-gray-500">
          Aucune activité récente
        </div>
        
        <div v-else class="space-y-4">
          <div
            v-for="activity in recentActivity"
            :key="activity.id"
            class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
            @click="navigateToActivity(activity)"
          >
            <div class="w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center">
              <component :is="getActivityIcon(activity.type)" class="w-5 h-5 text-primary-600" />
            </div>
            <div class="flex-1">
              <p class="text-sm text-gray-900">{{ activity.description }}</p>
              <p class="text-xs text-gray-500">{{ formatRelativeDate(activity.created_at) }}</p>
            </div>
            <ArrowRight class="w-4 h-4 text-gray-400" />
          </div>
        </div>
      </div>

      <!-- Member Since -->
      <div class="card p-6 text-center">
        <h3 class="text-lg font-semibold text-gray-900 mb-2">Membre depuis</h3>
        <p class="text-2xl text-primary-600">{{ formatDate(profileUser.created_at) }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useToast } from 'vue-toastification'
import axios from '@/utils/axios'
import { getMediaUrl } from '@/utils/axios'
import { format, formatDistanceToNow } from 'date-fns'
import { fr } from 'date-fns/locale'
import { User, ArrowLeft, ArrowRight, MessageSquare, Video, Image, Calendar, Activity } from 'lucide-vue-next'
import LoadingLogo from '@/components/LoadingLogo.vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const toast = useToast()

const loading = ref(true)
const profileUser = ref(null)
const userStats = ref({})
const recentActivity = ref([])

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

function formatRelativeDate(date) {
  if (!date) return ''
  return formatDistanceToNow(new Date(date), { addSuffix: true, locale: fr })
}

function getActivityIcon(type) {
  switch (type) {
    case 'post':
      return MessageSquare
    case 'vlog':
      return Video
    case 'album':
      return Image
    case 'event':
      return Calendar
    default:
      return Activity
  }
}

function navigateToActivity(activity) {
  if (activity.link) {
    router.push(activity.link)
  }
}

async function fetchProfile(userId) {
  loading.value = true
  try {
    const response = await axios.get(`/api/users/${userId}`)
    profileUser.value = response.data
    await fetchUserStats(userId)
    await fetchRecentActivity(userId)
  } catch (error) {
    console.error('Error fetching profile:', error)
    profileUser.value = null
    toast.error('Erreur lors du chargement du profil')
  } finally {
    loading.value = false
  }
}

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

async function fetchRecentActivity(userId) {
  try {
    const response = await axios.get(`/api/stats/activity/user/${userId}`)
    recentActivity.value = response.data.activity
  } catch (error) {
    console.error('Error fetching recent activity:', error)
  }
}

onMounted(async () => {
  const userId = route.params.id
  
  if (!userId) {
    toast.error('ID utilisateur manquant')
    router.push('/')
    return
  }
  
  // Empêcher de voir son propre profil ici
  if (parseInt(userId) === authStore.user?.id) {
    router.push('/profile')
    return
  }
  
  await fetchProfile(userId)
})
</script>
