<template>
  <div>
    <v-container fluid>
      <v-row>
        <v-col cols="12">
          <h1 class="text-h4 font-weight-bold mb-4">
            <v-icon left>mdi-account</v-icon>
            Welcome Back, {{ firstName }}
          </h1>
          <p class="text-body-1 mb-6">
            Manage users and portal settings for the MonacoUSA Portal.
          </p>
        </v-col>
      </v-row>

      <!-- Portal Status -->
      <v-row class="mb-6">
        <v-col cols="12" md="6">
          <v-card elevation="2">
            <v-card-text>
              <div class="d-flex justify-space-between align-center">
                <div>
                  <p class="text-caption text-medium-emphasis mb-1">Portal Status</p>
                  <p class="text-h5 font-weight-bold text-success">Online</p>
                </div>
                <v-icon color="success" size="40">mdi-check-circle</v-icon>
              </div>
            </v-card-text>
          </v-card>
        </v-col>

        <v-col cols="12" md="6">
          <v-card elevation="2">
            <v-card-text>
              <div class="d-flex justify-space-between align-center">
                <div>
                  <p class="text-caption text-medium-emphasis mb-1">Total Users</p>
                  <p class="text-h5 font-weight-bold">{{ userCount }}</p>
                </div>
                <v-icon color="primary" size="40">mdi-account-multiple</v-icon>
              </div>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- User Management -->
      <v-row class="mb-6">
        <v-col cols="12">
          <v-card elevation="2">
            <v-card-title>
              <v-icon left>mdi-account-group</v-icon>
              User Management
            </v-card-title>
            <v-card-text>
              <p class="mb-4">Manage user accounts, roles, and permissions for the MonacoUSA Portal.</p>
              
              <v-row>
                <v-col cols="12" md="4">
                  <v-btn
                    color="primary"
                    block
                    size="large"
                    @click="manageUsers"
                  >
                    <v-icon start>mdi-account-cog</v-icon>
                    Manage Users
                  </v-btn>
                </v-col>
                
                <v-col cols="12" md="4">
                  <v-btn
                    color="secondary"
                    variant="outlined"
                    block
                    size="large"
                    @click="viewAuditLogs"
                  >
                    <v-icon start>mdi-file-document-outline</v-icon>
                    View Audit Logs
                  </v-btn>
                </v-col>
                
                <v-col cols="12" md="4">
                  <v-btn
                    color="secondary"
                    variant="outlined"
                    block
                    size="large"
                    @click="portalSettings"
                  >
                    <v-icon start>mdi-cog</v-icon>
                    Portal Settings
                  </v-btn>
                </v-col>
              </v-row>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>


    </v-container>

    <!-- NocoDB Settings Dialog -->
    <NocoDBSettingsDialog
      v-model="showNocoDBSettings"
      @settings-saved="handleSettingsSaved"
    />
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'dashboard',
  middleware: 'auth-admin'
});

const { firstName } = useAuth();

// Reactive data
const userCount = ref(0);
const loading = ref(false);

const recentActivity = ref([
  {
    id: 1,
    title: 'User Account Created',
    description: 'New user account created for john.doe@monacousa.org',
    time: '2 hours ago',
    icon: 'mdi-account-plus',
    color: 'success'
  },
  {
    id: 2,
    title: 'Role Updated',
    description: 'User role updated from User to Board Member',
    time: '4 hours ago',
    icon: 'mdi-shield-account',
    color: 'warning'
  },
  {
    id: 3,
    title: 'System Backup',
    description: 'Automated system backup completed successfully',
    time: '1 day ago',
    icon: 'mdi-backup-restore',
    color: 'info'
  },
  {
    id: 4,
    title: 'Password Reset',
    description: 'Password reset requested for jane.smith@monacousa.org',
    time: '2 days ago',
    icon: 'mdi-key-change',
    color: 'primary'
  }
]);

// Load simplified admin stats (without system metrics)
const loadStats = async () => {
  try {
    loading.value = true;
    
    // Simple user count without complex system metrics
    const response = await $fetch<{ userCount: number }>('/api/admin/stats');
    userCount.value = response.userCount || 0;
    
    console.log('✅ Admin stats loaded:', { userCount: userCount.value });
  } catch (error) {
    console.error('❌ Failed to load admin stats:', error);
    // Use fallback data
    userCount.value = 25;
  } finally {
    loading.value = false;
  }
};

// Action methods (placeholders for now)
const manageUsers = () => {
  window.open('https://auth.monacousa.org', '_blank');
};

const viewAuditLogs = () => {
  console.log('Navigate to audit logs');
  // TODO: Implement audit logs navigation
};

const showNocoDBSettings = ref(false);

const portalSettings = () => {
  showNocoDBSettings.value = true;
};

const handleSettingsSaved = () => {
  console.log('NocoDB settings saved successfully');
};

const createUser = () => {
  console.log('Create new user');
  // TODO: Implement create user dialog/form
};

const generateReport = () => {
  console.log('Generate user report');
  // TODO: Implement report generation
};

const manageRoles = () => {
  console.log('Manage user roles');
  // TODO: Implement role management
};

const systemMaintenance = () => {
  console.log('System maintenance');
  // TODO: Implement maintenance mode
};

// Load stats on component mount
onMounted(async () => {
  await loadStats();
});
</script>

<style scoped>
.v-card {
  border-radius: 12px !important;
}

.v-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.3s ease;
}

.v-btn {
  text-transform: none !important;
  font-weight: 600;
}

.v-list-item {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.v-list-item:last-child {
  border-bottom: none;
}
</style>
