<template>
  <div class="dashboard">
    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="stat-card">
        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
          <i class="fas fa-server mr-2"></i>Total Environments
        </h3>
        <div class="text-3xl font-bold text-gray-900">{{ stats.totalEnvironments }}</div>
        <div class="text-sm text-green-600 mt-2">+{{ stats.enabledCount }} enabled</div>
      </div>
      
      <div class="stat-card">
        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
          <i class="fas fa-check-circle mr-2"></i>Enabled
        </h3>
        <div class="text-3xl font-bold text-gray-900">{{ stats.enabledCount }}</div>
        <div class="text-sm text-gray-600 mt-2">{{ enabledPercentage }}% of total</div>
      </div>
      
      <div class="stat-card">
        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
          <i class="fas fa-cloud mr-2"></i>Providers
        </h3>
        <div class="text-3xl font-bold text-gray-900">{{ stats.totalProviders }}</div>
        <div class="text-sm text-gray-600 mt-2">Multi-cloud</div>
      </div>
      
      <div class="stat-card">
        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
          <i class="fas fa-exclamation-triangle mr-2"></i>Active Alerts
        </h3>
        <div class="text-3xl font-bold text-gray-900">{{ alerts.length }}</div>
        <div class="text-sm mt-2" :class="alerts.length > 0 ? 'text-red-600' : 'text-green-600'">
          {{ alerts.length > 0 ? `${alerts.length} unacknowledged` : 'All clear' }}
        </div>
      </div>
    </div>

    <!-- Environments by Provider -->
    <div v-for="(envs, provider) in environmentsByProvider" :key="provider" class="mb-8">
      <div class="bg-white rounded-t-xl border-b-2 border-primary-500 px-6 py-4 flex justify-between items-center">
        <h2 class="text-2xl font-bold text-primary-600 flex items-center gap-2">
          <i :class="getProviderIcon(provider)"></i>
          {{ provider.toUpperCase() }} Environments
        </h2>
        <span class="text-gray-500">{{ envs.length }} environment(s)</span>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6 bg-white rounded-b-xl shadow-sm">
        <EnvironmentCard
          v-for="env in envs"
          :key="env.name"
          :environment="env"
          :status="envStatuses[env.name]"
          @deploy="handleDeploy"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import EnvironmentCard from '../components/EnvironmentCard.vue';
import type { Environment, DeploymentStatus, Alert } from '../../types';

const environments = ref<Environment[]>([]);
const envStatuses = ref<Record<string, DeploymentStatus>>({});
const alerts = ref<Alert[]>([]);
const stats = ref({
  totalEnvironments: 0,
  enabledCount: 0,
  totalProviders: 0,
});

const environmentsByProvider = computed(() => {
  const grouped: Record<string, Environment[]> = {};
  environments.value.forEach(env => {
    const provider = env.provider || 'unknown';
    if (!grouped[provider]) {
      grouped[provider] = [];
    }
    grouped[provider].push(env);
  });
  return grouped;
});

const enabledPercentage = computed(() => {
  if (stats.value.totalEnvironments === 0) return 0;
  return Math.round((stats.value.enabledCount / stats.value.totalEnvironments) * 100);
});

const getProviderIcon = (provider: string): string => {
  const icons: Record<string, string> = {
    azure: 'fab fa-microsoft',
    aws: 'fab fa-aws',
    gcp: 'fab fa-google',
    ibm: 'fab fa-ibm',
    oci: 'fas fa-cloud',
    onprem: 'fas fa-server',
  };
  return icons[provider] || 'fas fa-server';
};

const loadData = async () => {
  try {
    const response = await fetch('/api/environments');
    environments.value = await response.json();
    
    stats.value.totalEnvironments = environments.value.length;
    stats.value.enabledCount = environments.value.filter(e => e.enabled).length;
    stats.value.totalProviders = Object.keys(environmentsByProvider.value).length;
    
    // Load statuses for enabled environments
    for (const env of environments.value) {
      if (env.enabled) {
        const statusResponse = await fetch(`/api/environments/${env.name}/status`);
        envStatuses.value[env.name] = await statusResponse.json();
      }
    }
    
    // Load alerts
    const alertsResponse = await fetch('/api/alerts?unacknowledged_only=true');
    alerts.value = await alertsResponse.json();
  } catch (error) {
    console.error('Error loading data:', error);
  }
};

const handleDeploy = async (envName: string) => {
  try {
    const response = await fetch(`/api/environments/${envName}/deploy`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        strategy: 'blue-green',
        version: 'latest',
      }),
    });
    
    const data = await response.json();
    if (response.ok) {
      alert(`✅ Deployment queued: ${data.deployment_id}`);
      await loadData(); // Refresh data
    } else {
      alert(`❌ Error: ${data.error}`);
    }
  } catch (error) {
    console.error('Deployment error:', error);
    alert(`❌ Error: ${error}`);
  }
};

onMounted(() => {
  loadData();
  // Auto-refresh every 30 seconds
  setInterval(loadData, 30000);
});
</script>

<style scoped>
.dashboard {
  /* Additional component styles */
}
</style>

