import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import api from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { Cable, Unplug, ExternalLink, RefreshCw, Search } from 'lucide-react'

import { BACKEND_HOST } from '../config'

export default function Tunnels() {
  const [agents, setAgents] = useState([])
  const [allTunnels, setAllTunnels] = useState([]) // {agentId, agentName, agentStatus, ...tunnel}
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [search, setSearch] = useState('')

  const loadAll = async () => {
    setError('')
    try {
      const agentList = await api.getAgents()
      setAgents(agentList || [])

      const tunnelPromises = (agentList || []).map(async (agent) => {
        try {
          const resp = await api.getTunnels(agent.id)
          const list = resp?.tunnels || resp?.data?.tunnels || resp?.data || resp || []
          const tunnels = Array.isArray(list) ? list : []
          return tunnels.map((t) => ({
            ...t,
            agentId: agent.id,
            agentName: agent.name,
            agentIp: agent.ip,
            agentStatus: agent.status,
          }))
        } catch {
          return []
        }
      })

      const results = await Promise.all(tunnelPromises)
      setAllTunnels(results.flat())
    } catch (e) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadAll()
    const iv = setInterval(loadAll, 15000)
    return () => clearInterval(iv)
  }, [])

  const closeTunnel = async (agentId, tunnelId) => {
    try {
      await api.closeTunnel(agentId, tunnelId)
      setAllTunnels((prev) =>
        prev.filter((t) => !((t.id === tunnelId || t.tunnel_id === tunnelId) && t.agentId === agentId))
      )
    } catch (e) {
      setError(e.message)
    }
  }

  const closeAll = async () => {
    if (!confirm(`Alle ${allTunnels.length} Tunnel schliessen?`)) return
    for (const t of allTunnels) {
      const tid = t.id || t.tunnel_id
      await api.closeTunnel(t.agentId, tid).catch(() => {})
    }
    loadAll()
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <h1 className="text-xl font-bold text-white">Aktive Tunnel</h1>
          <span className="text-sm text-gray-500">
            {allTunnels.length} {allTunnels.length === 1 ? 'Tunnel' : 'Tunnel'} auf {new Set(allTunnels.map((t) => t.agentId)).size} Geraet(e)
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={loadAll}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 border border-gray-700 rounded text-sm text-gray-300 transition-colors"
          >
            <RefreshCw className="w-3.5 h-3.5" />
            Aktualisieren
          </button>
          {allTunnels.length > 0 && (
            <button
              onClick={closeAll}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-red-600/20 hover:bg-red-600/30 border border-red-800/50 rounded text-sm text-red-400 transition-colors"
            >
              <Unplug className="w-3.5 h-3.5" />
              Alle schliessen
            </button>
          )}
        </div>
      </div>

      <div className="relative">
        <Search className="absolute left-3 top-2.5 w-4 h-4 text-gray-500" />
        <input
          type="text"
          placeholder="Suchen (Geraet, IP, Ziel, Port)..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full bg-gray-900 border border-gray-800 rounded pl-10 pr-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-orange-500"
        />
      </div>

      {error && <div className="text-sm text-red-400 bg-red-900/20 rounded px-3 py-2 border border-red-800/50">{error}</div>}

      {loading ? (
        <div className="text-gray-500">Lade Tunnel aller Geraete...</div>
      ) : (() => {
        const filtered = search
          ? allTunnels.filter((t) => {
              const q = search.toLowerCase()
              const target = `${t.target_host || ''}:${t.target_port || ''}`
              return (t.agentName || '').toLowerCase().includes(q) ||
                (t.agentIp || '').toLowerCase().includes(q) ||
                target.toLowerCase().includes(q) ||
                String(t.proxy_port || t.local_port || '').includes(q)
            })
          : allTunnels
        return filtered.length === 0 ? (
        <div className="bg-gray-900 rounded-lg border border-gray-800 px-6 py-12 text-center">
          <Cable className="w-10 h-10 text-gray-700 mx-auto mb-3" />
          <div className="text-gray-500">Keine aktiven Tunnel</div>
          <div className="text-xs text-gray-600 mt-1">
            Tunnel koennen ueber die Geraete-Detailansicht erstellt werden
          </div>
        </div>
      ) : (
        <div className="bg-gray-900 rounded-lg border border-gray-800 overflow-x-auto">
          <table className="w-full text-sm whitespace-nowrap">
            <thead>
              <tr className="border-b border-gray-800 text-left text-gray-500 text-xs">
                <th className="px-4 py-2.5 font-medium">Geraet</th>
                <th className="px-4 py-2.5 font-medium">Ziel</th>
                <th className="px-4 py-2.5 font-medium">Lokaler Zugang</th>
                <th className="px-4 py-2.5 font-medium">Status</th>
                <th className="px-4 py-2.5 font-medium">Erstellt</th>
                <th className="px-4 py-2.5 font-medium text-right">Aktionen</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-800">
              {filtered.map((t) => {
                const tid = t.id || t.tunnel_id
                const proxyPort = t.proxy_port || t.local_port
                const target = t.target_host && t.target_port
                  ? `${t.target_host}:${t.target_port}`
                  : t.target || '—'
                const isWebGUI = String(t.target_port) === '4444'

                return (
                  <tr key={`${t.agentId}-${tid}`} className="hover:bg-gray-800/50">
                    <td className="px-4 py-2.5">
                      <Link to={`/agents/${t.agentId}`} className="flex items-center gap-2 hover:text-orange-400 transition-colors">
                        <StatusBadge status={t.agentStatus} size="dot" />
                        <div>
                          <div className="text-white text-sm">{t.agentName}</div>
                          <div className="text-xs text-gray-500">{t.agentIp}</div>
                        </div>
                      </Link>
                    </td>
                    <td className="px-4 py-2.5 text-white font-mono text-xs">
                      {target}
                      {isWebGUI && <span className="ml-2 text-xs text-orange-400">(WebGUI)</span>}
                      {String(t.target_port) === '22' && <span className="ml-2 text-xs text-blue-400">(SSH)</span>}
                    </td>
                    <td className="px-4 py-2.5">
                      <div className="flex items-center gap-2">
                        <span className="text-gray-400 font-mono text-xs">
                          {proxyPort ? `${BACKEND_HOST}:${proxyPort}` : '—'}
                        </span>
                        {isWebGUI && proxyPort && (
                          <a
                            href={`https://${BACKEND_HOST}:${proxyPort}`}
                            target="_blank"
                            rel="noopener"
                            className="text-orange-400 hover:text-orange-300"
                            title="WebGUI oeffnen"
                          >
                            <ExternalLink className="w-3.5 h-3.5" />
                          </a>
                        )}
                      </div>
                    </td>
                    <td className="px-4 py-2.5">
                      <span className="inline-flex items-center gap-1.5 text-xs text-green-400">
                        <span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse" />
                        aktiv
                      </span>
                    </td>
                    <td className="px-4 py-2.5 text-gray-500 text-xs">
                      {t.created_at ? new Date(t.created_at).toLocaleString('de-DE') : '—'}
                    </td>
                    <td className="px-4 py-2.5 text-right">
                      <button
                        onClick={() => closeTunnel(t.agentId, tid)}
                        className="text-red-400 hover:text-red-300 p-1 rounded hover:bg-red-900/30 transition-colors"
                        title="Tunnel schliessen"
                      >
                        <Unplug className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )
      })()}
    </div>
  )
}
