import { useEffect, useState, useMemo, useRef } from 'react'
import api from '../api/client'
import StatusBadge from '../components/StatusBadge'
import AgentPanel from '../components/AgentPanel'
import { Search, ChevronUp, ChevronDown, Plus, X, Settings2, BookOpen } from 'lucide-react'
import InstallGuide from '../components/InstallGuide'

const ALL_COLUMNS = [
  { id: 'customer', label: 'Kunde', default: true },
  { id: 'name', label: 'Name', default: true, locked: true },
  { id: 'hostname', label: 'Hostname', default: false },
  { id: 'version', label: 'Version', default: true },
  { id: 'wanip', label: 'WAN IP', default: true },
  { id: 'lanip', label: 'LAN IP', default: false },
  { id: 'uptime', label: 'Uptime', default: true },
  { id: 'cpu', label: 'CPU', default: true },
  { id: 'ram', label: 'RAM', default: true },
  { id: 'disk', label: 'Disk', default: true },
  { id: 'lastresponse', label: 'Letzter Kontakt', default: false },
  { id: 'gateways', label: 'Gateways', default: true },
  { id: 'agentversion', label: 'Agent Version', default: false },
]

const STORAGE_KEY = 'rmm-firewall-columns'

function loadColumns() {
  try {
    const saved = localStorage.getItem(STORAGE_KEY)
    if (saved) return JSON.parse(saved)
  } catch {}
  return ALL_COLUMNS.filter(c => c.default).map(c => c.id)
}

function saveColumns(cols) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(cols))
}

// Extract short version: "OPNsense 26.1.2_5 (amd64)" -> "26.1.2_5"
function shortVersion(v) {
  if (!v) return ''
  const m = v.match(/(\d+\.\d+[\w._-]*)/)
  return m ? m[1] : v
}

export default function Agents() {
  const [agents, setAgents] = useState([])
  const [customers, setCustomers] = useState([])
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(true)
  const [sortKey, setSortKey] = useState('customer')
  const [sortDir, setSortDir] = useState('asc')
  const [selectedId, setSelectedId] = useState(null)
  const [showAddDialog, setShowAddDialog] = useState(false)
  const [showInstallGuide, setShowInstallGuide] = useState(false)
  const [addResult, setAddResult] = useState(null)
  const [visibleCols, setVisibleCols] = useState(loadColumns)
  const [showColMenu, setShowColMenu] = useState(false)
  const colMenuRef = useRef(null)

  const reload = () => {
    Promise.all([api.getAgents(), api.getCustomers()])
      .then(([a, c]) => {
        setAgents(a || [])
        setCustomers(c || [])
      })
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    reload()
    const iv = setInterval(reload, 30000)
    return () => clearInterval(iv)
  }, [])

  const customerMap = useMemo(() => {
    const m = {}
    customers.forEach((c) => (m[c.id] = c))
    return m
  }, [customers])

  // Enrich agents with system data summaries
  const [agentDetails, setAgentDetails] = useState({})

  useEffect(() => {
    agents.forEach((a) => {
      if (!agentDetails[a.id]) {
        api.getAgent(a.id).then((d) => {
          setAgentDetails((prev) => ({ ...prev, [a.id]: d }))
        })
      }
    })
  }, [agents])

  const toggleSort = (key) => {
    if (sortKey === key) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc')
    } else {
      setSortKey(key)
      setSortDir('asc')
    }
  }

  // Close column menu on click outside
  useEffect(() => {
    const handler = (e) => {
      if (colMenuRef.current && !colMenuRef.current.contains(e.target)) setShowColMenu(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  const toggleCol = (id) => {
    const col = ALL_COLUMNS.find(c => c.id === id)
    if (col?.locked) return
    const next = visibleCols.includes(id) ? visibleCols.filter(c => c !== id) : [...visibleCols, id]
    setVisibleCols(next)
    saveColumns(next)
  }

  const isColVisible = (id) => visibleCols.includes(id)

  const enriched = useMemo(() => {
    return agents.map((a) => {
      const detail = agentDetails[a.id]
      const sys = detail?.system_data
      const cust = a.customer_id ? customerMap[a.customer_id] : null
      
      // Nur OPNsense/FreeBSD Agents anzeigen
      if (a.platform === 'linux' || a.platform === 'windows') return null

      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 gateways = sys?.gateways || []

      // WAN IP: find interface with WAN role AND a valid IPv4 address
      const ifaces = sys?.network_interfaces || []
      const isIPv4 = (ip) => ip && /^\d+\.\d+\.\d+\.\d+/.test(ip)
      const wanIface = ifaces.find(i => (i.role || '').toUpperCase() === 'WAN' && isIPv4(i.ip))
        || ifaces.find(i => (i.role || '').toUpperCase() === 'WAN' && i.ip)
      const lanIface = ifaces.find(i => (i.role || '').toUpperCase() === 'LAN' && isIPv4(i.ip))
        || ifaces.find(i => (i.role || '').toUpperCase() === 'LAN' && i.ip)
      const wanIp = wanIface?.ip || a.ip || ''
      const lanIp = lanIface?.ip || ''

      return {
        ...a,
        customer: cust,
        customerName: cust?.name || '',
        customerNumber: cust?.number || '',
        cpuPct: sys?.cpu?.usage_percent ?? null,
        ramPct,
        diskPct,
        uptime: sys?.uptime_seconds || 0,
        version: shortVersion(sys?.opnsense_version || a.opnsense_version || ''),
        gateways,
        wanIp,
        lanIp,
        sys,
      }
    }).filter(Boolean)
  }, [agents, agentDetails, customerMap])

  const filtered = useMemo(() => {
    let list = enriched
    if (search) {
      const q = search.toLowerCase()
      list = list.filter((a) =>
        a.name.toLowerCase().includes(q) ||
        a.ip.toLowerCase().includes(q) ||
        a.hostname.toLowerCase().includes(q) ||
        a.customerName.toLowerCase().includes(q) ||
        a.customerNumber.toLowerCase().includes(q)
      )
    }
    list.sort((a, b) => {
      let va, vb
      switch (sortKey) {
        case 'customer': va = a.customerNumber; vb = b.customerNumber; break
        case 'name': va = a.name; vb = b.name; break
        case 'ip': va = a.ip; vb = b.ip; break
        case 'version': va = a.version; vb = b.version; break
        case 'uptime': return sortDir === 'asc' ? a.uptime - b.uptime : b.uptime - a.uptime
        case 'cpu': return sortDir === 'asc' ? (a.cpuPct ?? 999) - (b.cpuPct ?? 999) : (b.cpuPct ?? -1) - (a.cpuPct ?? -1)
        case 'ram': return sortDir === 'asc' ? (a.ramPct ?? 999) - (b.ramPct ?? 999) : (b.ramPct ?? -1) - (a.ramPct ?? -1)
        case 'disk': return sortDir === 'asc' ? (a.diskPct ?? 999) - (b.diskPct ?? 999) : (b.diskPct ?? -1) - (a.diskPct ?? -1)
        case 'status': va = a.status; vb = b.status; break
        default: va = a.name; vb = b.name
      }
      if (typeof va === 'string') {
        const cmp = va.localeCompare(vb)
        return sortDir === 'asc' ? cmp : -cmp
      }
      return 0
    })
    return list
  }, [enriched, search, sortKey, sortDir])

  const SortHeader = ({ label, k, className = '' }) => (
    <th
      className={`px-3 py-2 font-medium cursor-pointer hover:text-gray-300 select-none ${className}`}
      onClick={() => toggleSort(k)}
    >
      <span className="inline-flex items-center gap-1">
        {label}
        {sortKey === k && (sortDir === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />)}
      </span>
    </th>
  )

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold text-white">Geraete ({agents.length})</h1>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowInstallGuide(true)}
            className="flex items-center gap-2 px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-white text-sm rounded transition-colors"
          >
            <BookOpen className="w-4 h-4" /> Installationsanleitung
          </button>
          <button
            onClick={() => { setShowAddDialog(true); setAddResult(null) }}
            className="flex items-center gap-2 px-3 py-1.5 bg-orange-600 hover:bg-orange-500 text-white text-sm rounded transition-colors"
          >
            <Plus className="w-4 h-4" /> Geraet hinzufuegen
          </button>
        </div>
      </div>

      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-2.5 w-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Suchen (Name, IP, Kunde)..."
            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>
        <div className="relative" ref={colMenuRef}>
          <button
            onClick={() => setShowColMenu(!showColMenu)}
            className="p-2 bg-gray-900 border border-gray-800 rounded hover:border-gray-600 text-gray-400 hover:text-white transition-colors"
            title="Spalten konfigurieren"
          >
            <Settings2 className="w-4 h-4" />
          </button>
          {showColMenu && (
            <div className="absolute right-0 top-full mt-1 z-50 bg-gray-900 border border-gray-700 rounded-lg shadow-xl py-2 w-52">
              <div className="px-3 py-1 text-xs text-gray-500 font-medium">Sichtbare Spalten</div>
              {ALL_COLUMNS.map(col => (
                <label
                  key={col.id}
                  className={`flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-800 ${col.locked ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                  <input
                    type="checkbox"
                    checked={visibleCols.includes(col.id)}
                    onChange={() => toggleCol(col.id)}
                    disabled={col.locked}
                    className="rounded border-gray-600 bg-gray-800 text-orange-500 focus:ring-orange-500 focus:ring-offset-0"
                  />
                  <span className="text-gray-300">{col.label}</span>
                </label>
              ))}
            </div>
          )}
        </div>
      </div>

      {loading ? (
        <div className="text-gray-500">Laden...</div>
      ) : (
        <div className="bg-gray-900 rounded-lg border border-gray-800 overflow-x-auto">
          <table className="w-full text-xs whitespace-nowrap">
            <thead>
              <tr className="border-b border-gray-800 text-left text-gray-500 text-xs">
                <th className="px-2 py-1.5 font-medium w-8"></th>
                {isColVisible('customer') && <SortHeader label="KUNDE" k="customer" />}
                {isColVisible('name') && <SortHeader label="NAME" k="name" />}
                {isColVisible('hostname') && <th className="px-2 py-1.5 font-medium">HOSTNAME</th>}
                {isColVisible('version') && <SortHeader label="VERSION" k="version" />}
                {isColVisible('wanip') && <th className="px-2 py-1.5 font-medium">WAN IP</th>}
                {isColVisible('lanip') && <th className="px-2 py-1.5 font-medium">LAN IP</th>}
                {isColVisible('uptime') && <SortHeader label="UPTIME" k="uptime" />}
                {isColVisible('cpu') && <SortHeader label="CPU" k="cpu" />}
                {isColVisible('ram') && <SortHeader label="RAM" k="ram" />}
                {isColVisible('disk') && <SortHeader label="DISK" k="disk" />}
                {isColVisible('lastresponse') && <th className="px-2 py-1.5 font-medium">LETZTER KONTAKT</th>}
                {isColVisible('gateways') && <th className="px-2 py-1.5 font-medium">GATEWAYS</th>}
                {isColVisible('agentversion') && <th className="px-2 py-1.5 font-medium">AGENT</th>}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-800">
              {filtered.map((a) => (
                <tr
                  key={a.id}
                  onClick={() => setSelectedId(a.id)}
                  className={`hover:bg-gray-800/50 transition-colors cursor-pointer ${selectedId === a.id ? 'bg-gray-800/70' : ''}`}
                >
                  <td className="px-2 py-1.5"><StatusBadge status={a.status} size="dot" /></td>
                  {isColVisible('customer') && (
                    <td className="px-2 py-1.5 text-gray-400">
                      {a.customer ? <span className="text-orange-400">{a.customerNumber}</span> : <span className="text-gray-600">—</span>}
                    </td>
                  )}
                  {isColVisible('name') && (
                    <td className="px-2 py-1.5 text-white font-medium">{a.name}</td>
                  )}
                  {isColVisible('hostname') && <td className="px-2 py-1.5 text-gray-400 text-xs">{a.hostname}</td>}
                  {isColVisible('version') && <td className="px-2 py-1.5 text-gray-400">{a.version || '—'}</td>}
                  {isColVisible('wanip') && <td className="px-2 py-1.5 text-gray-400">{a.wanIp || '—'}</td>}
                  {isColVisible('lanip') && <td className="px-2 py-1.5 text-gray-400">{a.lanIp || '—'}</td>}
                  {isColVisible('uptime') && <td className="px-2 py-1.5 text-gray-400">{a.uptime ? formatUptime(a.uptime) : '—'}</td>}
                  {isColVisible('cpu') && <td className="px-2 py-1.5"><MiniBar value={a.cpuPct} /></td>}
                  {isColVisible('ram') && <td className="px-2 py-1.5"><MiniBar value={a.ramPct} /></td>}
                  {isColVisible('disk') && <td className="px-2 py-1.5"><MiniBar value={a.diskPct} /></td>}
                  {isColVisible('lastresponse') && (
                    <td className="px-2 py-1.5 text-gray-500 text-xs">
                      {a.last_heartbeat ? new Date(a.last_heartbeat).toLocaleString('de-DE') : '—'}
                    </td>
                  )}
                  {isColVisible('gateways') && (
                    <td className="px-2 py-1.5">
                      {a.gateways.length > 0 ? (
                        <div className="flex flex-col gap-0.5">
                          {a.gateways.map((gw) => (
                            <span key={gw.name} className="inline-flex items-center gap-1 text-xs">
                              <span className={`w-1.5 h-1.5 rounded-full ${gwDotColor(gw.status)}`} />
                              <span className="text-gray-400">{gw.name}</span>
                            </span>
                          ))}
                        </div>
                      ) : '—'}
                    </td>
                  )}
                  {isColVisible('agentversion') && (
                    <td className="px-2 py-1.5 text-gray-500 text-xs">{a.agent_version || '—'}</td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div className="text-center py-8 text-gray-500">
              {search ? 'Keine Treffer' : 'Keine Geraete registriert'}
            </div>
          )}
        </div>
      )}

      {/* Detail Panel */}
      {selectedId && (
        <AgentPanel
          agentId={selectedId}
          customers={customers}
          onClose={() => setSelectedId(null)}
          onReload={reload}
        />
      )}

      {/* Installationsanleitung Dialog */}
      {showInstallGuide && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-gray-800 rounded-lg shadow-xl w-full max-w-3xl max-h-[85vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b border-gray-700">
              <h2 className="text-lg font-semibold text-white">Installationsanleitung</h2>
              <button onClick={() => setShowInstallGuide(false)} className="text-gray-400 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-4">
              <InstallGuide />
            </div>
          </div>
        </div>
      )}

      {/* Geraet hinzufuegen Dialog */}
      {showAddDialog && (
        <AddDeviceDialog
          customers={customers}
          result={addResult}
          onAdd={async (name, custId) => {
            const res = await api.preRegisterAgent(name, custId)
            setAddResult(res)
            reload()
          }}
          onClose={() => { setShowAddDialog(false); setAddResult(null) }}
        />
      )}
    </div>
  )
}

function AddDeviceDialog({ customers, result, onAdd, onClose }) {
  const [name, setName] = useState('')
  const [custId, setCustId] = useState('')
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async () => {
    if (!name.trim()) { setError('Name ist erforderlich'); return }
    setError('')
    setSubmitting(true)
    try {
      await onAdd(name.trim(), custId ? parseInt(custId) : null)
    } catch (e) {
      setError(e.message)
    }
    setSubmitting(false)
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60" onClick={onClose}>
      <div className="bg-gray-900 border border-gray-700 rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-3 border-b border-gray-800">
          <h2 className="text-lg font-semibold text-white">Geraet hinzufuegen</h2>
          <button onClick={onClose} className="text-gray-500 hover:text-white"><X className="w-5 h-5" /></button>
        </div>

        <div className="px-5 py-4 space-y-4">
          {!result ? (
            <>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Name *</label>
                <input
                  type="text"
                  value={name}
                  onChange={e => setName(e.target.value)}
                  placeholder="z.B. OPN-KUNDE.intra.example.net"
                  className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-orange-500"
                  autoFocus
                  onKeyDown={e => e.key === 'Enter' && handleSubmit()}
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Kunde (optional)</label>
                <select
                  value={custId}
                  onChange={e => setCustId(e.target.value)}
                  className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-orange-500"
                >
                  <option value="">Kein Kunde</option>
                  {customers.map(c => (
                    <option key={c.id} value={c.id}>{c.number} — {c.name}</option>
                  ))}
                </select>
              </div>
              {error && <p className="text-red-400 text-sm">{error}</p>}
              <button
                onClick={handleSubmit}
                disabled={submitting}
                className="w-full py-2 bg-orange-600 hover:bg-orange-500 disabled:opacity-50 text-white text-sm font-medium rounded transition-colors"
              >
                {submitting ? 'Wird angelegt...' : 'Geraet anlegen'}
              </button>
            </>
          ) : (
            <>
              <div className="bg-green-900/30 border border-green-800 rounded p-3 text-sm text-green-300">
                Geraet "{result.name}" erfolgreich angelegt (ID: {result.id?.substring(0, 12)}...)
              </div>
              <InstallGuide agentName={result.name} />
            </>
          )}
        </div>
      </div>
    </div>
  )
}

function gwDotColor(status) {
  const s = (status || '').toLowerCase()
  if (s === 'online' || s === 'none') return 'bg-green-500'
  if (s === 'offline' || s === 'down') return 'bg-red-500'
  return 'bg-yellow-500'
}

function MiniBar({ value }) {
  if (value === null || value === undefined) return <span className="text-gray-600 text-[10px]">—</span>
  const color = value > 90 ? 'bg-red-500' : value > 70 ? 'bg-yellow-500' : value > 50 ? 'bg-blue-500' : 'bg-green-500'
  return (
    <div className="flex items-center gap-1">
      <div className="w-10 h-1 bg-gray-800 rounded overflow-hidden">
        <div className={`h-full rounded ${color}`} style={{ width: `${Math.min(value, 100)}%` }} />
      </div>
      <span className="text-[10px] text-gray-400">{value.toFixed(0)}%</span>
    </div>
  )
}

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`
  return `${h}h ${m}m`
}
