<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <h1 class="text-3xl font-bold text-gray-900 mb-8">Statistiques du groupe</h1>

          <!-- Loading state -->
      <div v-if="loading" class="text-center py-12">
        <LoadingLogo size="large" text="Chargement des statistiques..." />
      </div>

    <!-- Stats content -->
    <div v-else>
      <!-- Overview Stats -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-gray-600">Membres actifs</p>
              <p class="text-2xl font-bold text-gray-900">{{ overview.total_users }}</p>
            </div>
            <Users class="w-8 h-8 text-primary-600" />
          </div>
        </div>

        <div class="card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-gray-600">Événements</p>
              <p class="text-2xl font-bold text-gray-900">{{ overview.total_events }}</p>
            </div>
            <Calendar class="w-8 h-8 text-success-600" />
          </div>
        </div>

        <div class="card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-gray-600">Albums</p>
              <p class="text-2xl font-bold text-gray-900">{{ overview.total_albums }}</p>
            </div>
            <Image class="w-8 h-8 text-blue-600" />
          </div>
        </div>

        <div class="card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-gray-600">Vlogs</p>
              <p class="text-2xl font-bold text-gray-900">{{ overview.total_vlogs }}</p>
            </div>
            <Film class="w-8 h-8 text-purple-600" />
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <!-- Attendance Stats -->
        <div class="card p-6">
          <h2 class="text-xl font-semibold text-gray-900 mb-6">Taux de présence</h2>
          
          <div v-if="attendanceStats.attendance_stats.length === 0" class="text-center py-8 text-gray-500">
            Aucune donnée de présence disponible
          </div>
          
          <div v-else class="space-y-4">
            <div
              v-for="(user, index) in attendanceStats.attendance_stats.slice(0, 5)"
              :key="user.user_id"
              class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
            >
              <div class="flex items-center space-x-3">
                <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center text-sm font-medium text-primary-600">
                  {{ index + 1 }}
                </div>
                <UserAvatar :user="user" size="md" :show-user-info="true" />
              </div>
              
              <div class="text-right">
                <div class="text-lg font-bold text-primary-600">{{ Math.round(user.attendance_rate) }}%</div>
                <div class="text-xs text-gray-500">{{ user.present_count }}/{{ user.total_past_events }} événements</div>
              </div>
            </div>
            
            <div v-if="attendanceStats.best_attendee" class="mt-4 p-3 bg-success-50 rounded-lg border border-success-200">
              <div class="flex items-center space-x-2">
                <Trophy class="w-5 h-5 text-success-600" />
                <span class="text-sm font-medium text-success-800">
                  🏆 {{ attendanceStats.best_attendee.full_name }} est le plus assidu avec {{ Math.round(attendanceStats.best_attendee.attendance_rate) }}% de présence !
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- Fun Stats -->
        <div class="card p-6">
          <h2 class="text-xl font-semibold text-gray-900 mb-6">Statistiques fun</h2>
          
          <div class="space-y-4">
            <!-- Most Active Poster -->
            <div v-if="funStats.most_active_poster" class="p-3 bg-blue-50 rounded-lg border border-blue-200">
              <div class="flex items-center space-x-2">
                <MessageSquare class="w-5 h-5 text-blue-600" />
                <div>
                  <p class="text-sm font-medium text-blue-800">Posteur le plus actif</p>
                  <p class="text-xs text-blue-600">{{ funStats.most_active_poster.full_name }} ({{ funStats.most_active_poster.post_count }} posts)</p>
                </div>
              </div>
            </div>

            <!-- Most Mentioned -->
            <div v-if="funStats.most_mentioned" class="p-3 bg-green-50 rounded-lg border border-green-200">
              <div class="flex items-center space-x-2">
                <AtSign class="w-5 h-5 text-green-600" />
                <div>
                  <p class="text-sm font-medium text-green-800">Le plus mentionné</p>
                  <p class="text-xs text-green-600">{{ funStats.most_mentioned.full_name }} ({{ funStats.most_mentioned.mention_count }} mentions)</p>
                </div>
              </div>
            </div>

            <!-- Biggest Vlogger -->
            <div v-if="funStats.biggest_vlogger" class="p-3 bg-purple-50 rounded-lg border border-purple-200">
              <div class="flex items-center space-x-2">
                <Film class="w-5 h-5 text-purple-600" />
                <div>
                  <p class="text-sm font-medium text-purple-800">Vlogger le plus prolifique</p>
                  <p class="text-xs text-purple-600">{{ funStats.biggest_vlogger.full_name }} ({{ funStats.biggest_vlogger.vlog_count }} vlogs)</p>
                </div>
              </div>
            </div>

            <!-- Photo Addict -->
            <div v-if="funStats.photo_addict" class="p-3 bg-yellow-50 rounded-lg border border-yellow-200">
              <div class="flex items-center space-x-2">
                <Image class="w-5 h-5 text-yellow-600" />
                <div>
                  <p class="text-sm font-medium text-yellow-800">Accro aux photos</p>
                  <p class="text-xs text-yellow-600">{{ funStats.photo_addict.full_name }} ({{ funStats.photo_addict.album_count }} albums)</p>
                </div>
              </div>
            </div>

            <!-- Event Organizer -->
            <div v-if="funStats.event_organizer" class="p-3 bg-red-50 rounded-lg border border-red-200">
              <div class="flex items-center space-x-2">
                <Calendar class="w-5 h-5 text-red-600" />
                <div>
                  <p class="text-sm font-medium text-red-800">Organisateur d'événements</p>
                  <p class="text-xs text-red-600">{{ funStats.event_organizer.full_name }} ({{ funStats.event_organizer.event_count }} événements)</p>
                </div>
              </div>
            </div>

            <!-- Most Viewed Vlog -->
            <div v-if="funStats.most_viewed_vlog" class="p-3 bg-indigo-50 rounded-lg border border-indigo-200">
              <div class="flex items-center space-x-2">
                <Eye class="w-5 h-5 text-indigo-600" />
                <div>
                  <p class="text-sm font-medium text-indigo-800">Vlog le plus vu</p>
                  <p class="text-xs text-indigo-600">{{ funStats.most_viewed_vlog.title }} ({{ funStats.most_viewed_vlog.views_count }} vues)</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Recent Activity -->
      <div class="card p-6 mt-8">
        <h2 class="text-xl font-semibold text-gray-900 mb-6">Activité récente (30 derniers jours)</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="text-center p-4 bg-gray-50 rounded-lg">
            <div class="text-2xl font-bold text-primary-600">{{ overview.recent_events || 0 }}</div>
            <div class="text-sm text-gray-600">Nouveaux événements</div>
          </div>
          
          <div class="text-center p-4 bg-gray-50 rounded-lg">
            <div class="text-2xl font-bold text-success-600">{{ overview.recent_posts || 0 }}</div>
            <div class="text-sm text-gray-600">Nouvelles publications</div>
          </div>
          
          <div class="text-center p-4 bg-gray-50 rounded-lg">
            <div class="text-2xl font-bold text-purple-600">{{ overview.recent_vlogs || 0 }}</div>
            <div class="text-sm text-gray-600">Nouveaux vlogs</div>
          </div>
        </div>
      </div>

      <!-- User Stats -->
      <div class="card p-6 mt-8">
        <h2 class="text-xl font-semibold text-gray-900 mb-6">Statistiques par utilisateur</h2>
        
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Utilisateur</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Taux de présence</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Publications</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Vlogs</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Albums</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Événements créés</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr
                v-for="user in userStats"
                :key="user.user.id"
                class="hover:bg-gray-50"
              >
                <td class="px-6 py-4 whitespace-nowrap">
                  <UserAvatar :user="user.user" size="md" :show-user-info="true" />
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="text-sm font-medium text-gray-900">{{ Math.round(user.user.attendance_rate) }}%</span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ user.content_stats.posts_count }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ user.content_stats.vlogs_count }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ user.content_stats.albums_count }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ user.content_stats.events_created }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'vue-toastification'
import axios from '@/utils/axios'
import UserAvatar from '@/components/UserAvatar.vue'
import {
  Users,
  Calendar,
  Image,
  Film,
  Trophy,
  MessageSquare,
  AtSign,
  Eye
} from 'lucide-vue-next'
import LoadingLogo from '@/components/LoadingLogo.vue'

const toast = useToast()

const loading = ref(true)
const overview = ref({})
const attendanceStats = ref({})
const funStats = ref({})
const userStats = ref([])

async function fetchStats() {
  try {
    // Fetch overview stats
    const overviewResponse = await axios.get('/api/stats/overview')
    overview.value = overviewResponse.data

    // Fetch attendance stats
    const attendanceResponse = await axios.get('/api/stats/attendance')
    attendanceStats.value = attendanceResponse.data

    // Fetch fun stats
    const funResponse = await axios.get('/api/stats/fun')
    funStats.value = funResponse.data

    // Fetch user stats for all users
    const usersResponse = await axios.get('/api/users')
    const userStatsPromises = usersResponse.data.map(async (user) => {
      try {
        const userStatsResponse = await axios.get(`/api/stats/user/${user.id}`)
        return userStatsResponse.data
      } catch (error) {
        console.error(`Error fetching stats for user ${user.id}:`, error)
        return {
          user: user,
          content_stats: { posts_count: 0, vlogs_count: 0, albums_count: 0, events_created: 0 }
        }
      }
    })

    const userStatsResults = await Promise.all(userStatsPromises)
    userStats.value = userStatsResults.sort((a, b) => b.user.attendance_rate - a.user.attendance_rate)

  } catch (error) {
    toast.error('Erreur lors du chargement des statistiques')
    console.error('Error fetching stats:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchStats()
})
</script>
