import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { getServers, serverAction, sendRcon, getServerLogs, getWhitelist, getFactorioCurrentSave } from '../api'
import { useUser } from '../context/UserContext'
import MetricsChart from '../components/MetricsChart'
import FactorioWorldManager from '../components/FactorioWorldManager'

const getServerLogo = (serverName) => {
  const name = serverName.toLowerCase()
  if (name.includes("minecraft") || name.includes("all the mods")) return "/minecraft.png"
  if (name.includes("factorio")) return "/factorio.png"
  if (name.includes("vrising") || name.includes("v rising")) return "/vrising.png"
  if (name.includes("zomboid")) return "/zomboid.png"
  return null
}
export default function ServerDetail() {
  const { serverId } = useParams()
  const navigate = useNavigate()
  const { token, isModerator } = useUser()
  const [server, setServer] = useState(null)
  const [loading, setLoading] = useState(true)
  
  const [activeTab, setActiveTab] = useState('overview')
  const [rconCommand, setRconCommand] = useState('')
  const [rconHistory, setRconHistory] = useState([])
  const [logs, setLogs] = useState('')
  const [whitelistPlayers, setWhitelistPlayers] = useState([])
  
  const [whitelistInput, setWhitelistInput] = useState('')
  const [whitelistLoading, setWhitelistLoading] = useState(false)
  const [currentSave, setCurrentSave] = useState(null)
  const [logsUpdated, setLogsUpdated] = useState(null)
  const logsRef = useRef(null)
  const rconRef = useRef(null)

  const fetchCurrentSave = async () => {
    if (token && serverId === 'factorio') {
      try {
        const result = await getFactorioCurrentSave(token)
        setCurrentSave(result)
      } catch (err) {
        console.error('Failed to fetch current save:', err)
      }
    }
  }

  const fetchServer = async () => {
    try {
      const servers = await getServers(token)
      const found = servers.find(s => s.id === serverId)
      if (found) {
        setServer(found); document.title = found.name + " | Zeasy GSM"
      } else {
        navigate('/')
      }
    } catch (err) {
      console.error(err)
      navigate('/')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchServer()
    fetchCurrentSave()
    const interval = setInterval(() => {
      fetchServer()
      fetchCurrentSave()
    }, 10000)
    return () => clearInterval(interval)
  }, [token, serverId])

  const handleAction = async (action) => {
    // Immediately set status locally
    const newStatus = action === 'start' ? 'starting' : (action === 'stop' ? 'stopping' : 'starting')
    setServer(prev => ({ ...prev, status: newStatus }))
    try {
      await serverAction(token, server.id, action)
      setTimeout(() => {
        fetchServer()
        
      }, 2000)
    } catch (err) {
      console.error(err)
      
    }
  }

  const handleRcon = async (e) => {
    e.preventDefault()
    if (!rconCommand.trim()) return
    const cmd = rconCommand
    setRconCommand('')
    try {
      const { response } = await sendRcon(token, server.id, cmd)
      setRconHistory([...rconHistory, { cmd, res: response, time: new Date() }])
    } catch (err) {
      setRconHistory([...rconHistory, { cmd, res: 'Error: ' + err.message, time: new Date(), error: true }])
    }
  }

  const fetchLogs = async () => {
    try {
      const data = await getServerLogs(token, server.id, 50)
      setLogs(data.logs || '')
      setLogsUpdated(new Date())
      if (logsRef.current) {
        logsRef.current.scrollTop = logsRef.current.scrollHeight
      }
    } catch (err) {
      console.error(err)
    }
  }

  useEffect(() => {
    if (activeTab === 'console' && isModerator && server) {
      fetchLogs()
      const interval = setInterval(fetchLogs, 5000)
      return () => clearInterval(interval)
    }
  }, [activeTab, isModerator, server])

  useEffect(() => {
    if (activeTab === 'whitelist' && isModerator && server?.type === 'minecraft') {
      fetchWhitelist()
    }
  }, [activeTab, server])

  useEffect(() => {
    if (rconRef.current) {
      rconRef.current.scrollTop = rconRef.current.scrollHeight
    }
  }, [rconHistory])

  
  const fetchWhitelist = async () => {
    if (!server?.hasRcon) return
    try {
      const { players } = await getWhitelist(token, server.id)
      setWhitelistPlayers(players)
    } catch (err) {
      console.error("Failed to fetch whitelist:", err)
    }
  }

  const addToWhitelist = async (e) => {
    e.preventDefault()
    if (!whitelistInput.trim()) return
    setWhitelistLoading(true)
    try {
      await sendRcon(token, server.id, 'whitelist add ' + whitelistInput.trim())
      setWhitelistInput('')
      await fetchWhitelist()
    } catch (err) {
      console.error('Failed to add to whitelist:', err)
    } finally {
      setWhitelistLoading(false)
    }
  }

  const removeFromWhitelist = async (player) => {
    setWhitelistLoading(true)
    try {
      await sendRcon(token, server.id, 'whitelist remove ' + player)
      await fetchWhitelist()
    } catch (err) {
      console.error('Failed to remove from whitelist:', err)
    } finally {
      setWhitelistLoading(false)
    }
  }

const formatUptime = (seconds) => {
    const days = Math.floor(seconds / 86400)
    const hours = Math.floor((seconds % 86400) / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    if (days > 0) return days + 'd ' + hours + 'h ' + minutes + 'm'
    return hours + 'h ' + minutes + 'm'
  }

  const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'metrics', label: 'Metrics' },
    ...(isModerator ? [
      { id: 'console', label: 'Console' },
    ] : []),
    ...(isModerator && server?.type === 'minecraft' ? [
      { id: 'whitelist', label: 'Whitelist' },
    ] : []),
    ...(isModerator && server?.type === 'factorio' ? [
      { id: 'worlds', label: 'Worlds' },
    ] : []),
  ]

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

  if (!server) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-neutral-400">Server not found</div>
      </div>
    )
  }

  const cpuPercent = Math.min(server.metrics.cpu, 100)
  const memPercent = Math.min(server.metrics.memory, 100)

  const getStatusBadge = () => {
    const status = server.status || (server.running ? 'online' : 'offline')
    switch (status) {
      case 'online':
        return { class: 'badge badge-success', text: 'Online' }
      case 'starting':
        return { class: 'badge badge-warning', text: 'Starting...' }
      case 'stopping':
        return { class: 'badge badge-warning', text: 'Stopping...' }
      default:
        return { class: 'badge badge-destructive', text: 'Offline' }
    }
  }

  const statusBadge = getStatusBadge()

  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 gap-4">
            <button
              onClick={() => navigate('/')}
              className="btn btn-ghost"
            >
              Back
            </button>
            <div className="flex-1">
              <div className="flex items-center gap-3">
                {getServerLogo(server.name) && <img src={getServerLogo(server.name)} alt="" className="h-8 w-8 object-contain" />}
                <h1 className="text-xl font-semibold text-white">{server.name}</h1>
                <span className={statusBadge.class}>
                  {statusBadge.text}
                </span>
              </div>
              {server.running && (
                <p className="text-sm text-neutral-400 mt-1">
                  Uptime: {formatUptime(server.metrics.uptime)}
                </p>
              )}
            </div>
          </div>

          {/* Tabs */}
          <div className="tabs mt-4">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={'tab ' + (activeTab === tab.id ? 'tab-active' : '')}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </header>

      {/* Content */}
      <main className="container-main py-6">
        {/* Overview Tab */}
        {activeTab === 'overview' && (
          <div className="space-y-6 tab-content">
            {/* Stats Grid */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="card p-4">
                <div className="text-sm text-neutral-400">CPU Usage</div>
                <div className="text-2xl font-semibold text-white mt-1">{server.metrics.cpu.toFixed(1)}%</div>
                <div className="progress mt-2">
                  <div className="progress-bar" style={{ width: cpuPercent + '%' }} />
                </div>
              </div>
              <div className="card p-4">
                <div className="text-sm text-neutral-400">Memory</div>
                <div className="text-2xl font-semibold text-white mt-1">
                  {server.metrics.memoryUsed?.toFixed(1)} {server.metrics.memoryUnit}
                </div>
                <div className="text-xs text-neutral-500 mt-1">
                  of {server.metrics.memoryTotal?.toFixed(1)} {server.metrics.memoryUnit}
                </div>
              </div>
              <div className="card p-4">
                <div className="text-sm text-neutral-400">Players</div>
                <div className="text-2xl font-semibold text-white mt-1">{server.players.online}</div>
                <div className="text-xs text-neutral-500 mt-1">
                  {server.players.max ? 'of ' + server.players.max + ' max' : 'No limit'}
                </div>
              </div>
              <div className="card p-4">
                <div className="text-sm text-neutral-400">CPU Cores</div>
                <div className="text-2xl font-semibold text-white mt-1">{server.metrics.cpuCores}</div>
              </div>
              {server.type === 'factorio' && currentSave?.save && (
                <div className="card p-4">
                  <div className="text-sm text-neutral-400">{server.running ? 'Current World' : 'Next World'}</div>
                  <div className="text-lg font-semibold text-white mt-1 truncate">{currentSave.save}</div>
                  {!server.running && currentSave.source === 'newest' && (
                    <div className="text-xs text-neutral-500 mt-1">newest save</div>
                  )}
                </div>
              )}
            </div>

            {/* Players List */}
            {server.players?.list?.length > 0 && (
              <div className="card p-4">
                <h3 className="text-sm font-medium text-neutral-300 mb-3">Online Players</h3>
                <div className="flex flex-wrap gap-2">
                  {server.players.list.map((player, i) => (
                    <span key={i} className="badge badge-secondary">{player}</span>
                  ))}
                </div>
              </div>
            )}

            {/* Power Controls */}
            {isModerator && (
              <div className="card p-4">
                <h3 className="text-sm font-medium text-neutral-300 mb-3">Server Controls</h3>

                <div className="flex flex-wrap gap-3">
                  {(server.status === 'online' || (server.running && server.status !== 'starting' && server.status !== 'stopping')) ? (
                    <>
                      <button
                        onClick={() => handleAction('stop')}
                        disabled={server.status === 'stopping' || server.status === 'starting'}
                        className="btn btn-destructive"
                      >
                        {server.status === 'stopping' ? 'Stopping...' : 'Stop Server'}
                      </button>
                      <button
                        onClick={() => handleAction('restart')}
                        disabled={server.status === 'stopping' || server.status === 'starting'}
                        className="btn btn-secondary"
                      >
                        {server.status === 'starting' ? 'Starting...' : 'Restart Server'}
                      </button>
                    </>
                  ) : (
                    <button
                      onClick={() => handleAction('start')}
                      disabled={server.status === 'stopping' || server.status === 'starting'}
                      className="btn btn-primary"
                    >
                      {server.status === 'starting' ? 'Starting...' : 'Start Server'}
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Metrics Tab */}
        {activeTab === 'metrics' && (
          <div className="tab-content"><MetricsChart serverId={server.id} serverName={server.name} expanded={true} /></div>
        )}

        {/* Console Tab - Logs + RCON */}
        {activeTab === 'console' && isModerator && (
          <div className="space-y-4 tab-content">
            {/* Logs */}
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-3">
                <span className="text-sm text-neutral-400">Server Logs (last 50 lines)</span>
                {logsUpdated && (
                  <span className="text-xs text-neutral-600">
                    Aktualisiert: {logsUpdated.toLocaleTimeString('de-DE')}
                  </span>
                )}
              </div>
              <button onClick={fetchLogs} className="btn btn-secondary">
                Refresh
              </button>
            </div>
            <div
              ref={logsRef}
              className="terminal p-4 logs-container text-xs text-neutral-300 whitespace-pre-wrap"
            >
              {logs || 'Loading...'}
            </div>

            {/* RCON History */}
            {rconHistory.length > 0 && (
              <div ref={rconRef} className="terminal p-4 max-h-40 overflow-y-auto">
                <div className="text-neutral-500 text-xs mb-2">RCON History</div>
                {rconHistory.map((entry, i) => (
                  <div key={i} className="mb-2 text-sm">
                    <div className="text-neutral-400">
                      <span className="text-neutral-600">[{entry.time.toLocaleTimeString('de-DE')}]</span> &gt; {entry.cmd}
                    </div>
                    <div className={'whitespace-pre-wrap pl-4 ' + (entry.error ? 'text-red-400' : 'text-neutral-300')}>
                      {entry.res}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* RCON Input */}
            {server.hasRcon && (
              <form onSubmit={handleRcon} className="flex gap-2">
                <input
                  type="text"
                  value={rconCommand}
                  onChange={(e) => setRconCommand(e.target.value)}
                  placeholder="RCON command..."
                  className="input flex-1"
                />
                <button type="submit" className="btn btn-primary">
                  Send
                </button>
              </form>
            )}
          </div>
        )}
      
        {/* Whitelist Tab - Minecraft only */}
        {activeTab === 'whitelist' && isModerator && server.type === 'minecraft' && (
          <div className="space-y-4 tab-content">
            <div className="card p-4">
              <h3 className="text-sm font-medium text-neutral-300 mb-3">Add to Whitelist</h3>
              <form onSubmit={addToWhitelist} className="flex gap-2">
                <input
                  type="text"
                  value={whitelistInput}
                  onChange={(e) => setWhitelistInput(e.target.value)}
                  placeholder="Minecraft username..."
                  className="input flex-1"
                  disabled={whitelistLoading || !server.running}
                />
                <button type="submit" className="btn btn-primary" disabled={whitelistLoading || !server.running}>
                  {whitelistLoading ? 'Adding...' : 'Add'}
                </button>
              </form>
            </div>

            <div className="card p-4">
              <div className="flex justify-between items-center mb-3">
                <h3 className="text-sm font-medium text-neutral-300">Whitelisted Players ({whitelistPlayers.length})</h3>
                <button onClick={fetchWhitelist} className="btn btn-ghost text-sm">
                  Refresh
                </button>
              </div>
              {whitelistPlayers.length > 0 ? (
                <div className="flex flex-wrap gap-2">
                  {whitelistPlayers.map((player, i) => (
                    <div key={i} className="flex items-center gap-1 bg-neutral-800 rounded-full pl-3 pr-1 py-1">
                      <span className="text-sm text-neutral-200">{player}</span>
                      <button
                        onClick={() => removeFromWhitelist(player)}
                        disabled={whitelistLoading || !server.running}
                        className="w-6 h-6 flex items-center justify-center rounded-full hover:bg-neutral-700 text-neutral-400 hover:text-red-400"
                      >
                        x
                      </button>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-neutral-500 text-sm">No players whitelisted</div>
              )}
            </div>
          </div>
        )}

        {/* Worlds Tab - Factorio only */}
        {activeTab === 'worlds' && isModerator && server.type === 'factorio' && (
          <div className="tab-content">
            {server.running || server.status === 'starting' || server.status === 'stopping' ? (
              <div className="card p-8 text-center">
                <div className="text-neutral-400 mb-2">World management is locked while the server is running</div>
                <div className="text-neutral-500 text-sm">Stop the server to manage saves</div>
              </div>
            ) : (
              <FactorioWorldManager
                server={server}
                token={token}
                onServerAction={fetchServer}
              />
            )}
          </div>
        )}
      </main>
    </div>
  )
}
