<template>
  <div class="besu-monitoring">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold">Besu 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>
      <p class="mt-4 text-gray-600">Loading metrics...</p>
    </div>

    <div v-else-if="metrics" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <MetricCard
        title="Block Number"
        :value="metrics.blockNumber.toLocaleString()"
        unit="blocks"
        icon="fas fa-cube"
        :status="metrics.syncStatus === 'synced' ? 'healthy' : 'degraded'"
      />
      
      <MetricCard
        title="Peer Count"
        :value="metrics.peerCount.toString()"
        unit="peers"
        icon="fas fa-users"
        :status="metrics.peerCount > 3 ? 'healthy' : 'degraded'"
      />
      
      <MetricCard
        title="Sync Status"
        :value="capitalize(metrics.syncStatus)"
        icon="fas fa-sync"
        :status="metrics.syncStatus === 'synced' ? 'healthy' : 'degraded'"
      />
      
      <MetricCard
        title="Gas Price"
        :value="metrics.gasPrice"
        icon="fas fa-gas-pump"
        status="healthy"
      />
      
      <MetricCard
        title="Pending Transactions"
        :value="metrics.pendingTransactions.toString()"
        unit="txns"
        icon="fas fa-clock"
        :status="metrics.pendingTransactions < 50 ? 'healthy' : 'degraded'"
      />
      
      <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="Disk Usage"
        :value="metrics.diskUsage.toFixed(1)"
        unit="%"
        icon="fas fa-hdd"
        :status="metrics.diskUsage < 80 ? 'healthy' : metrics.diskUsage < 90 ? 'degraded' : 'unhealthy'"
      />
      
      <MetricCard
        title="Chain ID"
        :value="metrics.chainId.toString()"
        icon="fas fa-link"
        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 { BesuMetrics, 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<BesuMetrics | 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/besu?environment=${selectedEnvironment.value}`);
    if (response.ok) {
      metrics.value = await response.json();
    }
  } catch (error) {
    console.error('Failed to load Besu 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;
  }
};

const capitalize = (str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

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

