import { useEffect, useState } from 'react'
import api from '../api/client'
import StatusBadge from './StatusBadge'
import {
  X, Cpu, MemoryStick, HardDrive, Clock, Network, Shield, Route,
  Globe, Key, Download, Terminal, Wifi,
} from 'lucide-react'

const tabs = [
  { id: 'overview', label: 'Uebersicht' },
  { id: 'interfaces', label: 'Interfaces' },
  { id: 'services', label: 'Dienste' },
  { id: 'vpn', label: 'VPN' },
  { id: 'routes', label: 'Routen' },
  { id: 'dhcp', label: 'DHCP' },
  { id: 'certs', label: 'Zertifikate' },
  { id: 'backups', label: 'Backups' },
]

export default function AgentPanel({ agentId, customers, onClose, onReload }) {
  const [data, setData] = useState(null)
  const [tab, setTab] = useState('overview')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(true)
    setTab('overview')
    api.getAgent(agentId).then(setData).finally(() => setLoading(false))
  }, [agentId])

  useEffect(() => {
    if (!data) return
    const iv = setInterval(() => {
      api.getAgent(agentId).then(setData)
    }, 30000)
    return () => clearInterval(iv)
  }, [agentId, data])

  if (loading) return <Panel onClose={onClose}><div className="p-6 text-gray-500">Laden...</div></Panel>
  if (!data) return <Panel onClose={onClose}><div className="p-6 text-red-400">Nicht gefunden</div></Panel>

  const { agent, system_data: sys, status } = data
  const cust = agent.customer_id ? customers.find((c) => c.id === agent.customer_id) : null

  return (
    <Panel onClose={onClose}>
      {/* Header */}
      <div className="px-6 py-4 bg-gradient-to-r from-gray-800 to-gray-900 border-b border-gray-700">
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-3">
              <h2 className="text-lg font-bold text-white">{agent.name}</h2>
              <StatusBadge status={status} />
            </div>
            {cust && (
              <div className="text-sm text-orange-400 mt-0.5">{cust.number} — {cust.name}</div>
            )}
            <div className="text-xs text-gray-500 mt-1">
              {agent.hostname} &middot; IP: {agent.ip} &middot; {sys?.opnsense_version || agent.opnsense_version || '—'}
            </div>
          </div>
          <button onClick={onClose} className="text-gray-400 hover:text-white">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 mt-4 overflow-x-auto text-xs">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`px-3 py-1.5 rounded-t whitespace-nowrap transition-colors ${
                tab === t.id
                  ? 'bg-gray-900 text-orange-400 border-t border-x border-gray-700'
                  : 'text-gray-400 hover:text-gray-200'
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6 space-y-4">
        {!sys ? (
          <div className="text-gray-500">Keine Systemdaten</div>
        ) : tab === 'overview' ? (
          <OverviewTab sys={sys} />
        ) : tab === 'interfaces' ? (
          <InterfacesTab sys={sys} />
        ) : tab === 'services' ? (
          <ServicesTab sys={sys} />
        ) : tab === 'vpn' ? (
          <VPNTab sys={sys} />
        ) : tab === 'routes' ? (
          <RoutesTab sys={sys} />
        ) : tab === 'dhcp' ? (
          <DHCPTab sys={sys} />
        ) : tab === 'certs' ? (
          <CertsTab sys={sys} />
        ) : tab === 'backups' ? (
          <BackupsTab agentId={agentId} />
        ) : null}
      </div>
    </Panel>
  )
}

function Panel({ onClose, children }) {
  return (
    <>
      <div className="fixed inset-0 z-40 bg-black/50" onClick={onClose} />
      <div className="fixed inset-y-0 right-0 z-50 w-full max-w-3xl bg-gray-900 border-l border-gray-800 flex flex-col shadow-2xl animate-slide-in">
        {children}
      </div>
      <style>{`
        @keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }
        .animate-slide-in { animation: slideIn 0.2s ease-out; }
      `}</style>
    </>
  )
}

function MetricCard({ icon: Icon, label, value, sub, bar, barColor }) {
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4">
      <div className="flex items-center gap-2 text-gray-500 mb-2">
        {Icon && <Icon className="w-4 h-4" />}
        <span className="text-xs uppercase">{label}</span>
      </div>
      <div className="text-xl font-bold text-white">{value}</div>
      {sub && <div className="text-xs text-gray-500 mt-0.5">{sub}</div>}
      {bar !== undefined && bar !== null && (
        <div className="mt-2 h-1.5 bg-gray-700 rounded overflow-hidden">
          <div className={`h-full rounded ${barColor || 'bg-blue-500'}`} style={{ width: `${Math.min(bar, 100)}%` }} />
        </div>
      )}
    </div>
  )
}

function OverviewTab({ sys }) {
  const rootDisk = sys.disks?.find((d) => d.mount_point === '/')
  const diskPct = rootDisk && rootDisk.total_bytes > 0
    ? (rootDisk.used_bytes / rootDisk.total_bytes * 100) : null
  const ramPct = sys.memory?.total_bytes > 0
    ? (sys.memory.used_bytes / sys.memory.total_bytes * 100) : null
  const cpuPct = sys.cpu?.usage_percent

  const barColor = (v) => v > 90 ? 'bg-red-500' : v > 70 ? 'bg-yellow-500' : v > 50 ? 'bg-orange-500' : 'bg-green-500'

  const ifaceCount = sys.network_interfaces?.filter((i) => i.status === 'active' || i.status === 'up').length || 0
  const gwCount = sys.gateways?.length || 0
  const wgCount = sys.wireguard_peers?.length || 0
  const routeCount = sys.routes?.length || 0
  const certCount = sys.certificates?.length || 0
  const svcRunning = sys.services?.filter((s) => s.running).length || 0
  const svcTotal = sys.services?.length || 0

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">System-Metriken</h3>
      <div className="grid grid-cols-2 gap-3">
        <MetricCard icon={Cpu} label="CPU Auslastung" value={cpuPct != null ? `${cpuPct.toFixed(1)}%` : '—'}
          sub={sys.cpu?.model} bar={cpuPct} barColor={barColor(cpuPct || 0)} />
        <MetricCard icon={MemoryStick} label="RAM Auslastung" value={ramPct != null ? `${ramPct.toFixed(1)}%` : '—'}
          sub={sys.memory ? `${formatBytes(sys.memory.used_bytes)} / ${formatBytes(sys.memory.total_bytes)}` : ''}
          bar={ramPct} barColor={barColor(ramPct || 0)} />
        <MetricCard icon={HardDrive} label="Festplatte" value={diskPct != null ? `${diskPct.toFixed(1)}%` : '—'}
          sub={rootDisk ? `${formatBytes(rootDisk.used_bytes)} / ${formatBytes(rootDisk.total_bytes)}` : ''}
          bar={diskPct} barColor={barColor(diskPct || 0)} />
        <MetricCard icon={Clock} label="Uptime" value={sys.uptime_seconds ? formatUptime(sys.uptime_seconds) : '—'} />
      </div>

      <h3 className="text-sm font-medium text-gray-300 mt-4">Firewall Status</h3>
      <div className="grid grid-cols-4 gap-3">
        <StatusCard icon={Shield} value={sys.opnsense_version || '—'} label="OPNsense" />
        <StatusCard icon={Network} value={ifaceCount} label="Interfaces" />
        <StatusCard icon={Globe} value={gwCount} label="Gateways" />
        <StatusCard icon={Wifi} value={wgCount} label="VPN Tunnel" />
        <StatusCard icon={Route} value={routeCount} label="Routen" />
        <StatusCard icon={Key} value={certCount} label="Zertifikate" />
        <StatusCard value={`${svcRunning}/${svcTotal}`} label="Dienste" />
      </div>

      {/* Gateways */}
      {sys.gateways && sys.gateways.length > 0 && (
        <>
          <h3 className="text-sm font-medium text-gray-300 mt-4">Gateways</h3>
          <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                  <th className="px-3 py-2">Name</th>
                  <th className="px-3 py-2">Gateway</th>
                  <th className="px-3 py-2">Status</th>
                  <th className="px-3 py-2">RTT</th>
                  <th className="px-3 py-2">Loss</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-700/50">
                {sys.gateways.map((gw) => (
                  <tr key={gw.name}>
                    <td className="px-3 py-2 text-white">{gw.name}</td>
                    <td className="px-3 py-2 text-gray-400">{gw.gateway}</td>
                    <td className="px-3 py-2">
                      <span className={gw.status === 'none' ? 'text-green-400' : 'text-yellow-400'}>
                        {gw.status === 'none' ? 'OK' : gw.status}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-gray-400">{gw.delay || '—'}</td>
                    <td className="px-3 py-2 text-gray-400">{gw.loss || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </>
  )
}

function StatusCard({ icon: Icon, value, label }) {
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-3 text-center">
      {Icon && <Icon className="w-5 h-5 mx-auto text-gray-500 mb-1" />}
      <div className="text-lg font-bold text-white">{value}</div>
      <div className="text-xs text-gray-500">{label}</div>
    </div>
  )
}

function InterfacesTab({ sys }) {
  const ifaces = sys.network_interfaces || []
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
            <th className="px-3 py-2">Interface</th>
            <th className="px-3 py-2">Status</th>
            <th className="px-3 py-2">MAC</th>
            <th className="px-3 py-2">Adressen</th>
            <th className="px-3 py-2">RX</th>
            <th className="px-3 py-2">TX</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-700/50">
          {ifaces.map((i) => (
            <tr key={i.name}>
              <td className="px-3 py-2 text-white font-mono text-xs">{i.name}</td>
              <td className="px-3 py-2">
                <span className={`text-xs ${i.status === 'active' || i.status === 'up' ? 'text-green-400' : 'text-gray-500'}`}>
                  {i.status || '—'}
                </span>
              </td>
              <td className="px-3 py-2 text-gray-400 font-mono text-xs">{i.mac || '—'}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">
                {i.addresses && i.addresses.length > 0
                  ? i.addresses.join(', ')
                  : '—'}
              </td>
              <td className="px-3 py-2 text-gray-400 text-xs">{formatBytes(i.rx_bytes)}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">{formatBytes(i.tx_bytes)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

function ServicesTab({ sys }) {
  const services = sys.services || []
  const running = services.filter((s) => s.running)
  const stopped = services.filter((s) => !s.running)
  return (
    <div className="space-y-3">
      <div className="text-sm text-gray-400">{running.length} aktiv / {stopped.length} inaktiv</div>
      <div className="flex flex-wrap gap-2">
        {services.map((svc) => (
          <span
            key={svc.name}
            className={`text-xs px-2 py-1 rounded ${
              svc.running
                ? 'bg-green-900/30 text-green-400 border border-green-800/50'
                : 'bg-gray-800 text-gray-500 border border-gray-700'
            }`}
          >
            {svc.name}
          </span>
        ))}
      </div>
    </div>
  )
}

function VPNTab({ sys }) {
  const peers = sys.wireguard_peers || []
  if (peers.length === 0) return <div className="text-gray-500">Keine WireGuard-Peers</div>
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
            <th className="px-3 py-2">Interface</th>
            <th className="px-3 py-2">Public Key</th>
            <th className="px-3 py-2">Endpoint</th>
            <th className="px-3 py-2">Transfer</th>
            <th className="px-3 py-2">Last Handshake</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-700/50">
          {peers.map((p, i) => (
            <tr key={i}>
              <td className="px-3 py-2 text-white font-mono text-xs">{p.interface || '—'}</td>
              <td className="px-3 py-2 text-gray-400 font-mono text-xs">{(p.public_key || '—').substring(0, 16)}...</td>
              <td className="px-3 py-2 text-gray-400 text-xs">{p.endpoint || '—'}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">
                {p.transfer_rx ? `RX: ${formatBytes(p.transfer_rx)} / TX: ${formatBytes(p.transfer_tx)}` : '—'}
              </td>
              <td className="px-3 py-2 text-gray-400 text-xs">{p.latest_handshake || '—'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

function RoutesTab({ sys }) {
  const routes = sys.routes || []
  if (routes.length === 0) return <div className="text-gray-500">Keine Routen</div>
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
            <th className="px-3 py-2">Ziel</th>
            <th className="px-3 py-2">Gateway</th>
            <th className="px-3 py-2">Flags</th>
            <th className="px-3 py-2">Interface</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-700/50">
          {routes.map((r, i) => (
            <tr key={i}>
              <td className="px-3 py-2 text-white font-mono text-xs">{r.destination}</td>
              <td className="px-3 py-2 text-gray-400 font-mono text-xs">{r.gateway}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">{r.flags}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">{r.interface_name || r.iface}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

function DHCPTab({ sys }) {
  const leases = sys.dhcp_leases || []
  if (leases.length === 0) return <div className="text-gray-500">Keine DHCP Leases</div>
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
            <th className="px-3 py-2">IP</th>
            <th className="px-3 py-2">MAC</th>
            <th className="px-3 py-2">Hostname</th>
            <th className="px-3 py-2">Ablauf</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-700/50">
          {leases.map((l, i) => (
            <tr key={i}>
              <td className="px-3 py-2 text-white font-mono text-xs">{l.ip || l.address}</td>
              <td className="px-3 py-2 text-gray-400 font-mono text-xs">{l.mac || l.hwaddr}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">{l.hostname || '—'}</td>
              <td className="px-3 py-2 text-gray-400 text-xs">{l.expires || l.expire || '—'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

function CertsTab({ sys }) {
  const certs = sys.certificates || []
  if (certs.length === 0) return <div className="text-gray-500">Keine Zertifikate</div>
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
            <th className="px-3 py-2">Name</th>
            <th className="px-3 py-2">Aussteller</th>
            <th className="px-3 py-2">Gueltig bis</th>
            <th className="px-3 py-2">Typ</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-700/50">
          {certs.map((c, i) => {
            const expires = c.not_after ? new Date(c.not_after) : null
            const isExpired = expires && expires < new Date()
            const soonExpires = expires && !isExpired && (expires - new Date()) < 30 * 86400000
            return (
              <tr key={i}>
                <td className="px-3 py-2 text-white text-xs">{c.name || c.subject || '—'}</td>
                <td className="px-3 py-2 text-gray-400 text-xs">{c.issuer || '—'}</td>
                <td className={`px-3 py-2 text-xs ${isExpired ? 'text-red-400' : soonExpires ? 'text-yellow-400' : 'text-gray-400'}`}>
                  {expires ? expires.toLocaleDateString('de-DE') : '—'}
                </td>
                <td className="px-3 py-2 text-gray-400 text-xs">{c.type || (c.is_ca ? 'CA' : 'Cert')}</td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}

function BackupsTab({ agentId }) {
  const [backups, setBackups] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.getBackups(agentId).then(setBackups).catch(() => {}).finally(() => setLoading(false))
  }, [agentId])

  const triggerBackup = async () => {
    await api.triggerBackup(agentId)
    setTimeout(() => {
      api.getBackups(agentId).then(setBackups)
    }, 3000)
  }

  if (loading) return <div className="text-gray-500">Laden...</div>
  return (
    <div className="space-y-3">
      <button
        onClick={triggerBackup}
        className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-600 hover:bg-orange-700 rounded text-sm text-white"
      >
        <Download className="w-4 h-4" />
        Backup jetzt erstellen
      </button>
      {backups.length === 0 ? (
        <div className="text-gray-500">Keine Backups vorhanden</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">ID</th>
                <th className="px-3 py-2">Erstellt</th>
                <th className="px-3 py-2">Groesse</th>
                <th className="px-3 py-2">Hash</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {backups.map((b) => (
                <tr key={b.id}>
                  <td className="px-3 py-2 text-white">{b.id}</td>
                  <td className="px-3 py-2 text-gray-400 text-xs">{new Date(b.created_at).toLocaleString('de-DE')}</td>
                  <td className="px-3 py-2 text-gray-400">{formatBytes(b.size)}</td>
                  <td className="px-3 py-2 text-gray-500 font-mono text-xs">{(b.hash || '').substring(0, 16)}...</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

function formatBytes(bytes) {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`
}

function formatUptime(seconds) {
  const d = Math.floor(seconds / 86400)
  const h = Math.floor((seconds % 86400) / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (d > 0) return `${d}d ${h}h ${m}m`
  return `${h}h ${m}m`
}
