import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { getServers } from '../api'
import { useUser } from '../context/UserContext'
import ServerCard from '../components/ServerCard'
import SettingsModal from '../components/SettingsModal'
import UserManagement from '../components/UserManagement'
import LoginModal from '../components/LoginModal'

export default function Dashboard({ onLogin, onLogout }) {
  const navigate = useNavigate()
  const { user, token, loading: userLoading, isSuperadmin, role } = useUser()
  const [servers, setServers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showSettings, setShowSettings] = useState(false)
  const [showUserMgmt, setShowUserMgmt] = useState(false)
  const [showLogin, setShowLogin] = useState(false)

  const isAuthenticated = !!token

  const fetchServers = async () => {
    try {
      const data = await getServers(token)
      setServers(data)
      setError('')
    } catch (err) {
      if (err.message.includes('401') || err.message.includes('403')) {
        if (isAuthenticated) {
          onLogout()
        }
      } else {
        setError('Verbindung zum Server fehlgeschlagen')
      }
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!userLoading) {
      fetchServers()
      const interval = setInterval(fetchServers, 10000)
      return () => clearInterval(interval)
    }
  }, [token, userLoading])

  const roleLabels = {
    user: 'Betrachter',
    moderator: 'Operator',
    superadmin: 'Admin'
  }

  if (userLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-neutral-400">Laden...</div>
      </div>
    )
  }

  const onlineCount = servers.filter(s => s.running).length
  document.title = 'Dashboard | Zeasy GSM'
  const totalPlayers = servers.reduce((sum, s) => sum + (s.players?.online || 0), 0)

  return (
    <div className="min-h-screen page-enter">
      {/* Header */}
      <header className="border-b border-neutral-800 bg-neutral-900/50 backdrop-blur-sm sticky top-0 z-10">
        <div className="container-main py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <a href="https://zeasy.software" target="_blank" rel="noopener noreferrer" className="relative block group"><img src="/navbarlogograuer.png" alt="Logo" className="h-8 transition-opacity duration-300 group-hover:opacity-0" /><img src="/navbarlogoweiß.png" alt="Logo" className="h-8 absolute top-0 left-0 opacity-0 transition-opacity duration-300 group-hover:opacity-100" /></a>
              <span className="text-xl font-semibold text-white hidden sm:inline">Gameserver Management</span>
            </div>
            <div className="hidden md:flex items-center gap-4 text-sm text-neutral-400">
              <span>
                <span className="text-white font-medium">{onlineCount}</span>/{servers.length} online
              </span>
              <span className="text-neutral-600">|</span>
              <span>
                <span className="text-white font-medium">{totalPlayers}</span> Spieler
              </span>
            </div>
            <div className="flex items-center gap-3">
              {isAuthenticated ? (
                <>
                  <div className="hidden sm:block text-right mr-2">
                    <div className="text-sm text-white">{user?.username}</div>
                    <div className="text-xs text-neutral-500">{roleLabels[role]}</div>
                  </div>
                  {isSuperadmin && (
                    <button
                      onClick={() => setShowUserMgmt(true)}
                      className="btn btn-ghost"
                    >
                      Benutzer
                    </button>
                  )}
                  <button
                    onClick={() => setShowSettings(true)}
                    className="btn btn-ghost"
                  >
                    Einstellungen
                  </button>
                  <button
                    onClick={onLogout}
                    className="btn btn-outline"
                  >
                    Abmelden
                  </button>
                </>
              ) : (
                <button
                  onClick={() => setShowLogin(true)}
                  className="btn btn-primary"
                >
                  Anmelden
                </button>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="container-main py-8">
        {error && (
          <div className="mb-6 alert alert-error fade-in">
            {error}
          </div>
        )}
        {loading ? (
          <div className="text-center py-12">
            <div className="text-neutral-400">Server werden geladen...</div>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {servers.map((server, index) => (
              <div
                key={server.id}
                className="fade-in-up"
                style={{ animationDelay: index * 50 + 'ms', animationFillMode: 'both' }}
              >
                <ServerCard
                  server={server}
                  onClick={() => navigate('/server/' + server.id)}
                  isAuthenticated={isAuthenticated}
                />
              </div>
            ))}
          </div>
        )}
      </main>

      {/* Modals */}
      {showSettings && (
        <SettingsModal onClose={() => setShowSettings(false)} />
      )}
      {showUserMgmt && (
        <UserManagement onClose={() => setShowUserMgmt(false)} />
      )}
      {showLogin && (
        <LoginModal onLogin={onLogin} onClose={() => setShowLogin(false)} />
      )}
    </div>
  )
}
