<template>
  <div class="firefly-monitoring">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold">Firefly Monitoring</h2>
      <div class="flex gap-4">
        <select
          v-model="selectedEnvironment"
          @change="$emit('environment-change', selectedEnvironment)"
          class="px-4 py-2 border border-gray-300 rounded-lg"
        >
          <option value="">All Environments</option>
          <option v-for="env in environments" :key="env.name" :value="env.name">
            {{ env.name }}
          </option>
        </select>
        <button @click="loadMetrics" class="btn btn-secondary">
          <i class="fas fa-sync-alt mr-2"></i>Refresh
        </button>
        <button @click="collectMetrics" class="btn btn-primary" :disabled="loading">
          <i class="fas fa-download mr-2"></i>Collect Metrics
        </button>
      </div>
    </div>

    <div v-if="loading" class="text-center py-8">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500 mx-auto"></div>
    </div>

    <div v-else-if="metrics" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <MetricCard
        title="Namespace Count"
        :value="metrics.namespaceCount.toString()"
        unit="namespaces"
        icon="fas fa-folder"
        status="healthy"
      />
      
      <MetricCard
        title="Active APIs"
        :value="metrics.activeAPIs.toString()"
        unit="APIs"
        icon="fas fa-code"
        status="healthy"
      />
      
      <MetricCard
        title="Total Transactions"
        :value="metrics.totalTransactions.toLocaleString()"
        unit="txns"
        icon="fas fa-exchange-alt"
        status="healthy"
      />
      
      <MetricCard
        title="Pending Transactions"
        :value="metrics.pendingTransactions.toString()"
        unit="txns"
        icon="fas fa-clock"
        :status="metrics.pendingTransactions < 30 ? 'healthy' : 'degraded'"
      />
      
      <MetricCard
        title="Failed Transactions"
        :value="metrics.failedTransactions.toString()"
        unit="txns"
        icon="fas fa-exclamation-triangle"
        :status="metrics.failedTransactions < 10 ? 'healthy' : metrics.failedTransactions < 20 ? 'degraded' : 'unhealthy'"
      />
      
      <MetricCard
        title="Average Latency"
        :value="metrics.averageLatency.toFixed(2)"
        unit="ms"
        icon="fas fa-tachometer-alt"
        :status="metrics.averageLatency < 300 ? 'healthy' : metrics.averageLatency < 600 ? 'degraded' : 'unhealthy'"
      />
      
      <MetricCard
        title="CPU Usage"
        :value="metrics.cpuUsage.toFixed(1)"
        unit="%"
        icon="fas fa-microchip"
        :status="metrics.cpuUsage < 80 ? 'healthy' : metrics.cpuUsage < 90 ? 'degraded' : 'unhealthy'"
      />
      
      <MetricCard
        title="Memory Usage"
        :value="metrics.memoryUsage.toFixed(1)"
        unit="%"
        icon="fas fa-memory"
        :status="metrics.memoryUsage < 85 ? 'healthy' : metrics.memoryUsage < 95 ? 'degraded' : 'unhealthy'"
      />
      
      <MetricCard
        title="Database Connections"
        :value="metrics.databaseConnections.toString()"
        unit="connections"
        icon="fas fa-database"
        status="healthy"
      />
    </div>

    <div v-else class="text-center py-8 text-gray-500">
      No metrics available. Click "Collect Metrics" to gather data.
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import MetricCard from './MetricCard.vue';
import type { FireflyMetrics, Environment } from '../../../types';

const props = defineProps<{
  environment?: string;
}>();

defineEmits<{
  'environment-change': [env: string];
}>();

const selectedEnvironment = ref(props.environment || '');
const environments = ref<Environment[]>([]);
const metrics = ref<FireflyMetrics | null>(null);
const loading = ref(false);

const loadEnvironments = async () => {
  try {
    const response = await fetch('/api/environments');
    if (response.ok) {
      environments.value = await response.json();
    }
  } catch (error) {
    console.error('Failed to load environments:', error);
  }
};

const loadMetrics = async () => {
  if (!selectedEnvironment.value) return;
  
  loading.value = true;
  try {
    const response = await fetch(`/api/monitoring/firefly?environment=${selectedEnvironment.value}`);
    if (response.ok) {
      metrics.value = await response.json();
    }
  } catch (error) {
    console.error('Failed to load Firefly metrics:', error);
  } finally {
    loading.value = false;
  }
};

const collectMetrics = async () => {
  if (!selectedEnvironment.value) {
    alert('Please select an environment first');
    return;
  }
  
  loading.value = true;
  try {
    const response = await fetch(`/api/monitoring/environments/${selectedEnvironment.value}/collect`, {
      method: 'POST',
    });
    if (response.ok) {
      await loadMetrics();
    }
  } catch (error) {
    console.error('Failed to collect metrics:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadEnvironments();
  if (selectedEnvironment.value) {
    loadMetrics();
  }
});
</script>

