import { useEffect, useState, useRef, useCallback } from 'react'
import { useLocation } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { usePermissions } from '../hooks/usePermissions'

const Home = () => {
  const { authFetch } = useAuth()
  const location = useLocation()
  const { isAdmin, hasFullAccess, accessibleSpaces } = usePermissions()
  const [data, setData] = useState(null)
  const [stats, setStats] = useState(null)
  const [loadingStats, setLoadingStats] = useState(true)
  const [lastUpdate, setLastUpdate] = useState(null)
  const intervalRef = useRef(null)
  const isMountedRef = useRef(true)
  
  // Prüfe ob User Berechtigungsgruppen hat
  const hasGroups = isAdmin || hasFullAccess || (accessibleSpaces && accessibleSpaces.length > 0)
  const message = location.state?.message
  const messageType = location.state?.type || 'info'
  
  // Lösche location.state nach dem ersten Anzeigen
  useEffect(() => {
    if (location.state?.message) {
      // Entferne die Nachricht aus dem state nach dem ersten Render
      window.history.replaceState({}, document.title, location.pathname)
    }
  }, [location.state, location.pathname])

  // Fetch stats function
  const fetchStats = useCallback(async (isInitial = false) => {
    try {
      if (isInitial) {
        setLoadingStats(true)
      }
      const response = await authFetch('/api/stats')
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const statsData = await response.json()
      if (isMountedRef.current) {
        setStats(statsData)
        setLoadingStats(false)
        setLastUpdate(new Date())
      }
    } catch (err) {
      console.error('Error fetching stats:', err)
      if (isMountedRef.current) {
        setLoadingStats(false)
      }
    }
  }, [])

  // Fetch health function
  const fetchHealth = useCallback(async () => {
    try {
      const response = await fetch('/api/health')
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const healthData = await response.json()
      if (isMountedRef.current) {
        setData(healthData)
      }
    } catch (err) {
      console.error('Error fetching health:', err)
    }
  }, [])

  // Handle visibility change - pause polling when tab is hidden
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.hidden) {
        // Tab is hidden, clear interval
        if (intervalRef.current) {
          clearInterval(intervalRef.current)
          intervalRef.current = null
        }
      } else {
        // Tab is visible, resume polling
        if (!intervalRef.current && isMountedRef.current) {
          // Fetch immediately when tab becomes visible
          authFetch('/api/stats')
            .then(res => res.json())
            .then(statsData => {
              if (isMountedRef.current) {
                setStats(statsData)
                setLastUpdate(new Date())
              }
            })
            .catch(err => console.error('Error fetching stats:', err))
          
          fetch('/api/health')
            .then(res => res.json())
            .then(healthData => {
              if (isMountedRef.current) {
                setData(healthData)
              }
            })
            .catch(err => console.error('Error fetching health:', err))
          
          // Resume polling
          intervalRef.current = setInterval(() => {
            if (isMountedRef.current) {
              authFetch('/api/stats')
                .then(res => res.json())
                .then(statsData => {
                  if (isMountedRef.current) {
                    setStats(statsData)
                    setLastUpdate(new Date())
                  }
                })
                .catch(err => console.error('Error fetching stats:', err))
              
              fetch('/api/health')
                .then(res => res.json())
                .then(healthData => {
                  if (isMountedRef.current) {
                    setData(healthData)
                  }
                })
                .catch(err => console.error('Error fetching health:', err))
            }
          }, 5000)
        }
      }
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [authFetch])

  useEffect(() => {
    isMountedRef.current = true
    
    // Define fetch functions inside useEffect to avoid dependency issues
    const fetchStatsInternal = async (isInitial = false) => {
      try {
        if (isInitial) {
          setLoadingStats(true)
        }
        const response = await authFetch('/api/stats')
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        const statsData = await response.json()
        if (isMountedRef.current) {
          setStats(statsData)
          setLoadingStats(false)
          setLastUpdate(new Date())
        }
      } catch (err) {
        console.error('Error fetching stats:', err)
        if (isMountedRef.current) {
          setLoadingStats(false)
        }
      }
    }

    const fetchHealthInternal = async () => {
      try {
        const response = await fetch('/api/health')
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        const healthData = await response.json()
        if (isMountedRef.current) {
          setData(healthData)
        }
      } catch (err) {
        console.error('Error fetching health:', err)
      }
    }
    
    // Initial fetch
    fetchHealthInternal()
    fetchStatsInternal(true) // Pass true for initial load to show loading state

    // Set up polling interval (5 seconds)
    intervalRef.current = setInterval(() => {
      if (isMountedRef.current) {
        fetchStatsInternal(false) // Pass false for background updates
        fetchHealthInternal()
      }
    }, 5000)

    // Cleanup on unmount
    return () => {
      isMountedRef.current = false
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
    }
  }, [authFetch]) // Include authFetch in dependencies

  return (
    <div className="p-8 min-h-full bg-gradient-to-r from-slate-700 to-slate-900">
      <div className="max-w-10xl mx-auto">
        <h1 className="text-4xl font-bold text-white mb-4">Willkommen</h1>
        <p className="text-lg text-slate-200 mb-8">
          Dies ist die Startseite der Certigo Addon Anwendung.
        </p>
        
        {/* Warnung wenn User keine Berechtigungsgruppen hat */}
        {(!hasGroups || message) && (
          <div className={`mb-6 p-4 rounded-lg border ${
            messageType === 'warning' 
              ? 'bg-yellow-500/20 border-yellow-500/50' 
              : 'bg-blue-500/20 border-blue-500/50'
          }`}>
            <div className="flex items-start gap-3">
              <div className={`text-2xl flex-shrink-0 ${
                messageType === 'warning' ? 'text-yellow-400' : 'text-blue-400'
              }`}>
                {messageType === 'warning' ? '⚠️' : 'ℹ️'}
              </div>
              <div className="flex-1">
                <p className={`font-semibold mb-1 ${
                  messageType === 'warning' ? 'text-yellow-300' : 'text-blue-300'
                }`}>
                  {messageType === 'warning' ? 'Keine Berechtigungsgruppe' : 'Information'}
                </p>
                <p className={`text-sm ${
                  messageType === 'warning' ? 'text-yellow-200' : 'text-blue-200'
                }`}>
                  {message || "Sie sind keiner Berechtigungsgruppe zugewiesen. Bitte kontaktieren Sie einen Administrator, um Zugriff auf die Anwendung zu erhalten."}
                </p>
              </div>
            </div>
          </div>
        )}
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          {/* Stats Dashboard */}
          <div className="bg-slate-800/80 backdrop-blur-sm rounded-lg shadow-xl border border-slate-600/50 p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-semibold text-white">
                Statistiken
              </h2>
              {lastUpdate && (
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                  <span className="text-xs text-slate-400">
                    {new Date(lastUpdate).toLocaleTimeString('de-DE', { 
                      hour: '2-digit', 
                      minute: '2-digit',
                      second: '2-digit'
                    })}
                  </span>
                </div>
              )}
            </div>
            {!stats && loadingStats ? (
              <p className="text-slate-400">Lade Statistiken...</p>
            ) : stats ? (
              <div className="grid grid-cols-1 gap-4">
                <div className="bg-gradient-to-br from-blue-500/20 to-blue-600/20 rounded-lg p-4 border border-blue-500/30">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-slate-300 mb-1">Spaces</p>
                      <p className="text-3xl font-bold text-white">{stats.spaces}</p>
                    </div>
                    <div className="w-12 h-12 bg-blue-500/20 rounded-full flex items-center justify-center">
                      <svg className="w-6 h-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                      </svg>
                    </div>
                  </div>
                </div>
                
                <div className="bg-gradient-to-br from-green-500/20 to-green-600/20 rounded-lg p-4 border border-green-500/30">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-slate-300 mb-1">FQDNs</p>
                      <p className="text-3xl font-bold text-white">{stats.fqdns}</p>
                    </div>
                    <div className="w-12 h-12 bg-green-500/20 rounded-full flex items-center justify-center">
                      <svg className="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
                      </svg>
                    </div>
                  </div>
                </div>
                
                <div className="bg-gradient-to-br from-purple-500/20 to-purple-600/20 rounded-lg p-4 border border-purple-500/30">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-slate-300 mb-1">CSRs</p>
                      <p className="text-3xl font-bold text-white">{stats.csrs}</p>
                    </div>
                    <div className="w-12 h-12 bg-purple-500/20 rounded-full flex items-center justify-center">
                      <svg className="w-6 h-6 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                    </div>
                  </div>
                </div>
                
                <div className="bg-gradient-to-br from-yellow-500/20 to-yellow-600/20 rounded-lg p-4 border border-yellow-500/30">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-slate-300 mb-1">Zertifikate</p>
                      <p className="text-3xl font-bold text-white">{stats.certificates || 0}</p>
                    </div>
                    <div className="w-12 h-12 bg-yellow-500/20 rounded-full flex items-center justify-center">
                      <svg className="w-6 h-6 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                      </svg>
                    </div>
                  </div>
                </div>
                
                <div className="bg-gradient-to-br from-cyan-500/20 to-cyan-600/20 rounded-lg p-4 border border-cyan-500/30">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-slate-300 mb-1">Benutzer</p>
                      <p className="text-3xl font-bold text-white">{stats.users || 0}</p>
                    </div>
                    <div className="w-12 h-12 bg-cyan-500/20 rounded-full flex items-center justify-center">
                      <svg className="w-6 h-6 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <p className="text-slate-400">Fehler beim Laden der Statistiken</p>
            )}
          </div>

          {/* System Status */}
          <div className="bg-slate-800/80 backdrop-blur-sm rounded-lg shadow-xl border border-slate-600/50 p-6">
            <h2 className="text-2xl font-semibold text-white mb-4">
              System Status
            </h2>
            {data ? (
              <div className="space-y-2">
                <p className="text-slate-200">
                  <span className="font-medium">Status:</span>{' '}
                  <span className="text-green-400">{data.status}</span>
                </p>
                <p className="text-slate-200">
                  <span className="font-medium">Nachricht:</span> {data.message}
                </p>
              </div>
            ) : (
              <p className="text-slate-400">Lade Daten...</p>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default Home

