<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Bot, Code2, Server, Shield, Search, Terminal, Users, Wifi, WifiOff } from '@lucide/vue'
import { apiFetch } from '../services/api'

const router = useRouter()

interface AgentCard {
  id: string
  name: string
  role: string
  description: string
  tags: string[]
  color: string
  icon: string
  model?: string
  statusLabel?: string
  statusKind?: 'connected' | 'thinking' | 'blocked' | 'ready' | 'stale' | 'error' | 'unsupported'
  statusDetail?: string | null
  isActive?: boolean
  progress?: number
  currentTask?: string | null
}

interface GatewayRuntimeInfo {
  reachable: boolean
  version?: string | null
  requiredVersion?: string | null
  versionPinned: boolean
  versionMatches: boolean
  versionStatus: 'matched' | 'drift' | 'missing' | 'unpinned' | 'unknown' | 'error'
  message?: string | null
  warning?: string | null
}

const fallbackAgents: AgentCard[] = [
  {
    id: 'iris',
    name: 'Iris',
    role: 'Chief of Staff',
    description: 'Koordiniert, delegiert, hält das Team tight. Die erste Anlaufstelle zwischen Boss und Maschine.',
    tags: ['Orchestration', 'Delegation', 'Approval'],
    color: '#7c6cff',
    icon: 'bot',
  },
  {
    id: 'programmer',
    name: 'Programmer',
    role: 'Lead Developer',
    description: 'Implementiert Features, schreibt Code, führt Builds und Tests aus. Arbeitet autonom im Scope.',
    tags: ['Coding', 'Development', 'Builds'],
    color: '#4f7cff',
    icon: 'code',
  },
  {
    id: 'architekt',
    name: 'Architekt',
    role: 'Infrastructure Engineer',
    description: 'Verantwortlich für Docker, Nginx, Deployment und VPS-Infrastruktur.',
    tags: ['Infrastructure', 'Deployment', 'Docker'],
    color: '#4f7cff',
    icon: 'server',
  },
  {
    id: 'reviewer',
    name: 'Reviewer',
    role: 'Code QA',
    description: 'Prüft Code auf Bugs, Sicherheit und Wartbarkeit. Fixt Probleme eigenständig.',
    tags: ['QA', 'Security', 'Code Review'],
    color: '#fbbf24',
    icon: 'shield',
  },
  {
    id: 'researcher',
    name: 'Researcher',
    role: 'Research Analyst',
    description: 'Recherchiert, analysiert Quellen, prüft Fakten. Nur Lese-Rechte, keine Aktionen.',
    tags: ['Research', 'Analysis', 'Fact-Checking'],
    color: '#b557f6',
    icon: 'search',
  },
  {
    id: 'executor',
    name: 'Executor',
    role: 'Host Executor',
    description: 'Führt Host-Kommandos auf dem VPS aus. Nur auf Iris-Befehl, niemals eigeninitiativ.',
    tags: ['Execution', 'Docker', 'VPS'],
    color: '#34d6f5',
    icon: 'terminal',
  },
]

const agents = ref<AgentCard[]>([])
const gateway = ref<GatewayRuntimeInfo | null>(null)
const loading = ref(false)
const error = ref('')

const agentCount = computed(() => agents.value.length)
const hasAgents = computed(() => agents.value.length > 0)
const gatewayWarning = computed(() => gateway.value?.warning || '')
const gatewayLabel = computed(() => {
  if (!gateway.value) return 'Gateway wird geprüft'
  if (!gateway.value.reachable) return gateway.value.message || 'Gateway offline'
  switch (gateway.value.versionStatus) {
    case 'matched':
      return `Pinned ${gateway.value.requiredVersion}`
    case 'drift':
      return 'Version drift'
    case 'missing':
      return 'Version fehlt'
    case 'unknown':
      return 'Version unbekannt'
    case 'unpinned':
      return gateway.value.version ? `Detected ${gateway.value.version}` : 'Unpinned'
    default:
      return gateway.value.message || 'Gateway online'
  }
})
const gatewayChipClass = computed(() => {
  if (!gateway.value) return 'neutral'
  if (!gateway.value.reachable) return 'error'
  if (gateway.value.warning) return 'warn'
  return 'ok'
})

async function loadMissionControl() {
  loading.value = true
  error.value = ''
  try {
    const [agentsResponse, gatewayResponse] = await Promise.all([
      apiFetch('/api/dashboard/agents'),
      apiFetch('/api/dashboard/gateway'),
    ])

    if (agentsResponse.ok) {
      const data = await agentsResponse.json()
      agents.value = data.map((item: any) => enrichAgent(item))
    } else {
      error.value = await readErrorMessage(agentsResponse, 'Agenten konnten nicht geladen werden')
    }

    if (gatewayResponse.ok) {
      gateway.value = await gatewayResponse.json()
    } else {
      const gatewayError = await readErrorMessage(gatewayResponse, 'Gateway-Status konnte nicht geladen werden')
      error.value = error.value ? `${error.value} · ${gatewayError}` : gatewayError
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Mission Control konnte nicht geladen werden'
  } finally {
    loading.value = false
  }
}

function enrichAgent(item: any): AgentCard {
  const fallback = fallbackAgents.find(a => a.id === item.id)
  return {
    id: item.id,
    name: item.name || fallback?.name || item.id,
    role: item.role || fallback?.role || 'Agent',
    description: item.description || fallback?.description || 'OpenClaw agent',
    tags: item.tags?.length ? item.tags : fallback?.tags ?? [],
    color: fallback?.color ?? '#6f6aa0',
    icon: fallback?.icon ?? 'bot',
    model: item.model,
    statusLabel: item.statusLabel,
    statusKind: item.statusKind,
    statusDetail: item.statusDetail,
    isActive: item.isActive,
    progress: item.progress,
    currentTask: item.currentTask,
  }
}

async function readErrorMessage(response: Response, fallback: string) {
  try {
    const payload = await response.json()
    return payload?.error || payload?.message || fallback
  } catch {
    return fallback
  }
}

function goToAgent(id: string) {
  router.push(`/agents/${id}`)
}

function resolveIcon(iconName: string) {
  switch (iconName) {
    case 'bot': return Bot
    case 'code': return Code2
    case 'server': return Server
    case 'shield': return Shield
    case 'search': return Search
    case 'terminal': return Terminal
    default: return Bot
  }
}

function statusTone(agent: AgentCard) {
  switch (agent.statusKind) {
    case 'connected': return 'connected'
    case 'thinking': return 'thinking'
    case 'blocked': return 'blocked'
    case 'stale': return 'stale'
    case 'error': return 'error'
    case 'unsupported': return 'unsupported'
    default: return agent.isActive ? 'connected' : 'ready'
  }
}

function statusCopy(agent: AgentCard) {
  if (agent.statusDetail) return agent.statusDetail
  if (agent.currentTask) return agent.currentTask
  switch (agent.statusKind) {
    case 'connected': return 'Session ist erreichbar.'
    case 'thinking': return 'Agent plant den nächsten Schritt.'
    case 'blocked': return 'Agent wartet auf Entblockung.'
    case 'stale': return 'Es gab länger kein neues Signal.'
    case 'error': return 'Gateway konnte den Session-Status nicht lesen.'
    case 'unsupported': return 'Session meldet einen nicht unterstützten Zustand.'
    default: return 'Keine aktive Aufgabe gemeldet.'
  }
}

onMounted(loadMissionControl)
</script>

<template>
  <div class="agents-page">
    <!-- Header -->
    <div class="page-header">
      <div class="header-icon-wrap">
        <Users :size="22" />
      </div>
      <div class="header-text">
        <h1>Agents</h1>
        <p class="header-subtitle">{{ agentCount }} agents · {{ gatewayLabel }}</p>
      </div>
      <div class="gateway-chip" :class="gatewayChipClass">
        <Wifi v-if="gateway?.reachable" :size="13" />
        <WifiOff v-else :size="13" />
        {{ gateway?.version || gatewayLabel }}
      </div>
    </div>

    <div v-if="loading" class="load-error">Lade Gateway-Status...</div>
    <div v-else-if="error" class="load-error">{{ error }}</div>
    <div v-if="gatewayWarning" class="gateway-warning">
      {{ gatewayWarning }}
    </div>

    <!-- Agent grid -->
    <div v-if="hasAgents" class="agents-grid">
      <article
        v-for="agent in agents"
        :key="agent.id"
        class="agent-card"
        :class="`status-${statusTone(agent)}`"
        :style="{ '--card-color': agent.color }"
        @click="goToAgent(agent.id)"
      >
        <div class="card-stripe" :style="{ background: agent.color }"></div>
        <div class="card-content">
          <div class="card-header">
            <div class="card-icon-wrap" :style="{ background: `${agent.color}18`, color: agent.color }">
              <component :is="resolveIcon(agent.icon)" :size="18" />
            </div>
            <div class="card-info">
              <h3 class="card-name">{{ agent.name }}</h3>
              <span class="card-role">{{ agent.role }}</span>
            </div>
          </div>
          <p class="card-desc">{{ agent.description }}</p>
          <div class="agent-runtime">
            <span :class="['runtime-dot', statusTone(agent)]"></span>
            <span>{{ agent.statusLabel || (agent.isActive ? 'Arbeitet' : 'Bereit') }}</span>
            <span v-if="agent.model" class="runtime-model">{{ agent.model }}</span>
          </div>
          <p class="runtime-detail">{{ statusCopy(agent) }}</p>
          <div class="progress-track">
            <span :style="{ width: `${agent.progress ?? 0}%`, background: agent.color }"></span>
          </div>
          <div class="card-tags">
            <span
              v-for="tag in agent.tags"
              :key="tag"
              class="card-tag"
              :style="{ background: `${agent.color}14`, color: agent.color, borderColor: `${agent.color}24` }"
            >
              {{ tag }}
            </span>
          </div>
        </div>
        <div class="card-footer">
          <span class="footer-label">View Profile</span>
          <span class="footer-arrow">&rarr;</span>
        </div>
      </article>
    </div>
    <div v-else-if="!loading" class="empty-state">
      <h3>Keine Agenten sichtbar</h3>
      <p>Mission Control hat aktuell keine Agenten aus dem Backend erhalten. Prüfe Gateway-Erreichbarkeit und Agent-Konfiguration.</p>
    </div>
  </div>
</template>

<style scoped>
.agents-page {
  max-width: 960px;
  margin: 0 auto;
  padding-bottom: 40px;
}

/* Page header */
.page-header {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 28px;
}
.header-icon-wrap {
  width: 44px;
  height: 44px;
  display: grid;
  place-items: center;
  border-radius: 11px;
  background: rgba(139, 124, 246, 0.1);
  color: var(--a-mid);
  flex-shrink: 0;
}
.header-text h1 {
  margin: 0 0 2px;
  font-size: 22px;
  font-weight: 600;
  color: var(--tx);
}
.header-subtitle {
  margin: 0;
  font-size: 11px;
  color: var(--tx-3);
}
.gateway-chip {
  margin-left: auto;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 9px;
  border: 1px solid var(--line);
  border-radius: 7px;
  color: var(--tx-2);
  font-size: 10px;
}
.gateway-chip.ok {
  color: var(--st-work);
  border-color: rgba(81, 212, 154, .25);
}
.gateway-chip.warn {
  color: var(--st-queue);
  border-color: rgba(229, 176, 94, .28);
}
.gateway-chip.error {
  color: var(--st-block);
  border-color: rgba(242, 155, 155, .3);
}
.load-error {
  margin-bottom: 14px;
  color: var(--st-queue);
  font-size: 11px;
}
.gateway-warning,
.empty-state {
  margin-bottom: 16px;
  padding: 14px 16px;
  border-radius: 11px;
  border: 1px solid rgba(229, 176, 94, .24);
  background: rgba(229, 176, 94, .08);
  color: var(--st-queue);
  font-size: 11px;
  line-height: 1.5;
}
.empty-state {
  border-color: var(--line);
  background: rgba(255,255,255,.03);
  color: var(--tx-2);
}
.empty-state h3 {
  margin: 0 0 6px;
  font-size: 14px;
  color: var(--tx);
}
.empty-state p {
  margin: 0;
}

/* Agent grid */
.agents-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 14px;
}

/* Agent card */
.agent-card {
  background: var(--panel);
  border: 1px solid var(--line);
  border-radius: 11px;
  cursor: pointer;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: border-color 0.2s, box-shadow 0.2s, transform 0.15s;
}
.agent-card:hover {
  border-color: var(--card-color);
  box-shadow: 0 0 20px color-mix(in srgb, var(--card-color) 10%, transparent);
  transform: translateY(-2px);
}
.agent-card.status-error {
  border-color: rgba(242, 155, 155, .22);
}
.agent-card.status-unsupported {
  border-color: rgba(229, 176, 94, .22);
}
.agent-card.status-stale {
  border-color: rgba(244, 164, 96, .22);
}

.card-stripe {
  height: 3px;
  flex-shrink: 0;
}

.card-content {
  padding: 16px 16px 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.card-icon-wrap {
  width: 36px;
  height: 36px;
  display: grid;
  place-items: center;
  border-radius: var(--r);
  flex-shrink: 0;
}

.card-info {
  flex: 1;
  min-width: 0;
}

.card-name {
  margin: 0 0 1px;
  font-size: 13px;
  font-weight: 600;
  color: var(--tx);
}

.card-role {
  display: block;
  font-size: 9px;
  color: var(--tx-3);
  letter-spacing: 0.02em;
}

.card-desc {
  font-size: 10.5px;
  color: var(--tx-3);
  line-height: 1.5;
  margin: 0 0 10px;
  flex: 1;
}
.agent-runtime {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  color: var(--tx-2);
  font-size: 9.5px;
  min-width: 0;
}
.runtime-dot {
  width: 7px;
  height: 7px;
  border-radius: 999px;
  background: var(--tx-3);
  flex-shrink: 0;
}
.runtime-dot.on {
  background: var(--st-work);
}
.runtime-dot.connected { background: var(--st-work); }
.runtime-dot.thinking { background: var(--a-blue); }
.runtime-dot.blocked { background: var(--st-block); }
.runtime-dot.stale { background: var(--st-queue); }
.runtime-dot.error { background: var(--st-block); }
.runtime-dot.unsupported { background: var(--st-queue); }
.runtime-dot.ready { background: var(--tx-3); }
.runtime-model {
  margin-left: auto;
  max-width: 46%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
  color: var(--tx-3);
}
.runtime-detail {
  margin: 0 0 10px;
  min-height: 28px;
  color: var(--tx-3);
  font-size: 10px;
  line-height: 1.4;
}
.progress-track {
  height: 3px;
  border-radius: 999px;
  background: rgba(255,255,255,.06);
  overflow: hidden;
  margin-bottom: 10px;
}
.progress-track span {
  display: block;
  height: 100%;
  border-radius: inherit;
}

.card-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.card-tag {
  display: inline-block;
  font-size: 8.5px;
  font-weight: 600;
  padding: 2px 7px;
  border-radius: 4px;
  border: 1px solid transparent;
  letter-spacing: 0.02em;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 4px;
  padding: 8px 16px;
  border-top: 1px solid var(--line);
  font-size: 9px;
  font-weight: 600;
  color: var(--tx-3);
  text-transform: uppercase;
  letter-spacing: 0.06em;
  transition: color 0.15s;
}
.agent-card:hover .card-footer {
  color: var(--card-color);
}

.footer-arrow {
  font-size: 12px;
  line-height: 1;
}

/* Responsive */
@media (max-width: 820px) {
  .agents-grid {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 540px) {
  .agents-grid {
    grid-template-columns: 1fr;
  }
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
