'use client'

import { useState, useEffect, useCallback } from 'react'
import { CommunicationStats, ActiveMeeting, RecentRoom } from './types'

const API_BASE = '/api/admin/communication'

export function useCommunicationStats() {
  const [stats, setStats] = useState<CommunicationStats | null>(null)
  const [activeMeetings, setActiveMeetings] = useState<ActiveMeeting[]>([])
  const [recentRooms, setRecentRooms] = useState<RecentRoom[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchStats = useCallback(async () => {
    try {
      const response = await fetch(`${API_BASE}/stats`)
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }
      const data = await response.json()
      setStats(data)
      setActiveMeetings(data.active_meetings || [])
      setRecentRooms(data.recent_rooms || [])
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Verbindungsfehler')
      // Set mock data for display purposes when API unavailable
      setStats({
        matrix: {
          total_users: 0,
          active_users: 0,
          total_rooms: 0,
          active_rooms: 0,
          messages_today: 0,
          messages_this_week: 0,
          status: 'offline'
        },
        jitsi: {
          active_meetings: 0,
          total_participants: 0,
          meetings_today: 0,
          average_duration_minutes: 0,
          peak_concurrent_users: 0,
          total_minutes_today: 0,
          status: 'offline'
        },
        last_updated: new Date().toISOString()
      })
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchStats()
  }, [fetchStats])

  // Auto-refresh every 15 seconds
  useEffect(() => {
    const interval = setInterval(fetchStats, 15000)
    return () => clearInterval(interval)
  }, [fetchStats])

  return { stats, activeMeetings, recentRooms, loading, error, fetchStats }
}
