<template>
  <div class="admin-panel">
    <div class="mb-8">
      <h1 class="text-3xl font-bold mb-2">Admin Panel</h1>
      <p class="text-gray-600">Manage services, providers, and environments</p>
    </div>

    <!-- Login Form (if not authenticated) -->
    <div v-if="!isAuthenticated" class="max-w-md mx-auto card">
      <h2 class="text-2xl font-bold mb-4">Admin Login</h2>
      <form @submit.prevent="handleLogin" class="space-y-4">
        <div>
          <label for="admin-username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
          <input
            id="admin-username"
            name="username"
            v-model="loginForm.username"
            type="text"
            required
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
            placeholder="admin"
            aria-label="Username"
          />
        </div>
        <div>
          <label for="admin-password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
          <input
            id="admin-password"
            name="password"
            v-model="loginForm.password"
            type="password"
            required
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500"
            placeholder="Enter password"
            aria-label="Password"
          />
        </div>
        <button type="submit" class="btn btn-primary w-full">Login</button>
      </form>
    </div>

    <!-- Admin Dashboard (if authenticated) -->
    <div v-else class="space-y-8">
      <!-- Tabs -->
      <div class="border-b border-gray-200">
        <nav class="flex space-x-8">
          <button
            @click="activeTab = 'services'"
            :class="[
              'py-4 px-1 border-b-2 font-medium text-sm',
              activeTab === 'services'
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            ]"
          >
            Services
          </button>
          <button
            @click="activeTab = 'providers'"
            :class="[
              'py-4 px-1 border-b-2 font-medium text-sm',
              activeTab === 'providers'
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            ]"
          >
            Providers
          </button>
          <button
            @click="activeTab = 'environments'"
            :class="[
              'py-4 px-1 border-b-2 font-medium text-sm',
              activeTab === 'environments'
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            ]"
          >
            Environments
          </button>
          <button
            @click="activeTab = 'audit'"
            :class="[
              'py-4 px-1 border-b-2 font-medium text-sm',
              activeTab === 'audit'
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            ]"
          >
            Audit Logs
          </button>
        </nav>
      </div>

      <!-- Services Tab -->
      <div v-if="activeTab === 'services'" class="space-y-4">
        <div class="flex justify-between items-center">
          <h2 class="text-2xl font-bold">Services</h2>
          <button @click="loadServices" class="btn btn-secondary">
            <i class="fas fa-sync-alt mr-2"></i>Refresh
          </button>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="service in services"
            :key="service.service_name"
            class="card"
          >
            <div class="flex justify-between items-start mb-4">
              <h3 class="text-lg font-semibold">{{ service.service_name }}</h3>
              <label class="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  :checked="service.enabled"
                  @change="toggleService(service.service_name, $event.target.checked)"
                  class="sr-only peer"
                />
                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
            </div>
            <div class="text-sm text-gray-500">
              <div>Updated: {{ formatDate(service.updated_at) }}</div>
              <div v-if="service.updated_by">By: {{ service.updated_by }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Providers Tab -->
      <div v-if="activeTab === 'providers'" class="space-y-4">
        <div class="flex justify-between items-center">
          <h2 class="text-2xl font-bold">Providers</h2>
          <button @click="loadProviders" class="btn btn-secondary">
            <i class="fas fa-sync-alt mr-2"></i>Refresh
          </button>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="provider in providers"
            :key="provider.provider_name"
            class="card"
          >
            <div class="flex justify-between items-start mb-4">
              <h3 class="text-lg font-semibold capitalize">{{ provider.provider_name }}</h3>
              <label class="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  :checked="provider.enabled"
                  @change="toggleProvider(provider.provider_name, $event.target.checked)"
                  class="sr-only peer"
                />
                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
            </div>
            <div class="text-sm text-gray-500">
              <div>Updated: {{ formatDate(provider.updated_at) }}</div>
              <div v-if="provider.updated_by">By: {{ provider.updated_by }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Environments Tab -->
      <div v-if="activeTab === 'environments'" class="space-y-4">
        <div class="flex justify-between items-center">
          <h2 class="text-2xl font-bold">Environments</h2>
          <button @click="loadEnvironments" class="btn btn-secondary">
            <i class="fas fa-sync-alt mr-2"></i>Refresh
          </button>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="env in environments"
            :key="env.name"
            class="card"
          >
            <div class="flex justify-between items-start mb-4">
              <div>
                <h3 class="text-lg font-semibold">{{ env.name }}</h3>
                <div class="text-sm text-gray-500">
                  {{ env.provider }} • {{ env.region }}
                </div>
              </div>
              <label class="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  :checked="env.enabled"
                  @change="toggleEnvironment(env.name, $event.target.checked)"
                  class="sr-only peer"
                />
                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
            </div>
            <div class="text-sm">
              <span :class="env.enabled ? 'text-green-600' : 'text-gray-400'">
                {{ env.enabled ? 'Enabled' : 'Disabled' }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- Audit Logs Tab -->
      <div v-if="activeTab === 'audit'" class="space-y-4">
        <div class="flex justify-between items-center">
          <h2 class="text-2xl font-bold">Audit Logs</h2>
          <button @click="loadAuditLogs" class="btn btn-secondary">
            <i class="fas fa-sync-alt mr-2"></i>Refresh
          </button>
        </div>
        <div class="card overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Timestamp</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Action</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Resource</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP Address</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="log in auditLogs" :key="log.id">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(log.timestamp) }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ log.admin_user }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ log.action }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ log.resource_type }}{{ log.resource_id ? `: ${log.resource_id}` : '' }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ log.ip_address }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Logout Button -->
      <div class="flex justify-end">
        <button @click="handleLogout" class="btn btn-secondary">
          <i class="fas fa-sign-out-alt mr-2"></i>Logout
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { io, Socket } from 'socket.io-client';
import type { ServiceConfig, ProviderConfig, Environment, AuditLogEntry } from '../../types';

const isAuthenticated = ref(false);
const adminToken = ref<string | null>(localStorage.getItem('adminToken'));
const activeTab = ref<'services' | 'providers' | 'environments' | 'audit'>('services');

const loginForm = ref({ username: '', password: '' });
const services = ref<ServiceConfig[]>([]);
const providers = ref<ProviderConfig[]>([]);
const environments = ref<Environment[]>([]);
const auditLogs = ref<AuditLogEntry[]>([]);
const socket = ref<Socket | null>(null);

const checkAuth = () => {
  isAuthenticated.value = !!adminToken.value;
  if (isAuthenticated.value) {
    loadData();
  }
};

const handleLogin = async () => {
  try {
    const response = await fetch('/api/admin/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(loginForm.value),
    });

    if (response.ok) {
      const data = await response.json();
      adminToken.value = data.token;
      localStorage.setItem('adminToken', data.token);
      isAuthenticated.value = true;
      loadData();
    } else {
      alert('Invalid credentials');
    }
  } catch (error) {
    console.error('Login error:', error);
    alert('Login failed');
  }
};

const handleLogout = () => {
  adminToken.value = null;
  localStorage.removeItem('adminToken');
  isAuthenticated.value = false;
};

const getAuthHeaders = () => ({
  'Content-Type': 'application/json',
  'X-Admin-Token': adminToken.value || '',
});

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

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

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 loadAuditLogs = async () => {
  try {
    const response = await fetch('/api/admin/audit-logs?limit=100', { headers: getAuthHeaders() });
    if (response.ok) {
      auditLogs.value = await response.json();
    }
  } catch (error) {
    console.error('Failed to load audit logs:', error);
  }
};

const loadData = () => {
  loadServices();
  loadProviders();
  loadEnvironments();
  loadAuditLogs();
};

const toggleService = async (serviceName: string, enabled: boolean) => {
  try {
    const response = await fetch(`/api/admin/services/${serviceName}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({ enabled }),
    });

    if (response.ok) {
      await loadServices();
      await loadAuditLogs();
    } else {
      alert('Failed to update service');
    }
  } catch (error) {
    console.error('Failed to toggle service:', error);
    alert('Failed to update service');
  }
};

const toggleProvider = async (providerName: string, enabled: boolean) => {
  try {
    const response = await fetch(`/api/admin/providers/${providerName}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({ enabled }),
    });

    if (response.ok) {
      await loadProviders();
      await loadAuditLogs();
    } else {
      alert('Failed to update provider');
    }
  } catch (error) {
    console.error('Failed to toggle provider:', error);
    alert('Failed to update provider');
  }
};

const toggleEnvironment = async (envName: string, enabled: boolean) => {
  try {
    const response = await fetch(`/api/admin/environments/${envName}/toggle`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({ enabled }),
    });

    if (response.ok) {
      await loadEnvironments();
      await loadAuditLogs();
    } else {
      alert('Failed to update environment');
    }
  } catch (error) {
    console.error('Failed to toggle environment:', error);
    alert('Failed to update environment');
  }
};

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString();
};

onMounted(() => {
  checkAuth();
  
  // Initialize WebSocket connection for real-time updates
  if (isAuthenticated.value) {
    socket.value = io(window.location.origin);
    socket.value.on('connect', () => {
      console.log('Connected to WebSocket server');
      socket.value?.emit('join-admin');
    });
    
    socket.value.on('admin-update', (data: { type: string; data: any; timestamp: string }) => {
      console.log('Admin update received:', data);
      
      // Refresh relevant data based on update type
      if (data.type === 'service-updated') {
        loadServices();
        loadAuditLogs();
      } else if (data.type === 'provider-updated') {
        loadProviders();
        loadAuditLogs();
      } else if (data.type === 'environment-updated') {
        loadEnvironments();
        loadAuditLogs();
      }
    });
    
    socket.value.on('disconnect', () => {
      console.log('Disconnected from WebSocket server');
    });
  }
});

onUnmounted(() => {
  if (socket.value) {
    socket.value.disconnect();
  }
});
</script>

<style scoped>
.admin-panel {
  /* Component styles */
}
</style>

