<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="3">
                  <v-btn
                    color="primary"
                    block
                    size="large"
                    @click="navigateTo('/dashboard/member-list')"
                  >
                    <v-icon start>mdi-account-cog</v-icon>
                    Manage Users
                  </v-btn>
                </v-col>
                
                <v-col cols="12" md="3">
                  <v-btn
                    color="success"
                    variant="outlined"
                    block
                    size="large"
                    @click="showCreateUserDialog = true"
                  >
                    <v-icon start>mdi-account-plus</v-icon>
                    Create User Account
                  </v-btn>
                </v-col>
                
                <v-col cols="12" md="3">
                  <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="3">
                  <v-btn
                    color="secondary"
                    variant="outlined"
                    block
                    size="large"
                    @click="showAdminConfig = true"
                  >
                    <v-icon start>mdi-cog</v-icon>
                    Portal Settings
                  </v-btn>
                </v-col>
              </v-row>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- NocoDB Configuration -->
      <v-row class="mb-6">
        <v-col cols="12">
          <v-card elevation="2">
            <v-card-title>
              <v-icon left>mdi-database-cog</v-icon>
              Database Configuration
            </v-card-title>
            <v-card-text>
              <p class="mb-4">Configure the NocoDB database connection for the Member Management system.</p>
              
              <v-row>
                <v-col cols="12" md="6">
                  <v-btn
                    color="info"
                    variant="outlined"
                    block
                    size="large"
                    @click="showNocoDBSettings = true"
                  >
                    <v-icon start>mdi-database-settings</v-icon>
                    Configure NocoDB
                  </v-btn>
                </v-col>
                
                <v-col cols="12" md="6">
                  <div class="d-flex align-center" style="height: 100%;">
                    <v-chip color="success" variant="tonal" size="small">
                      <v-icon start size="14">mdi-database</v-icon>
                      Ready for configuration
                    </v-chip>
                  </div>
                </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"
    />

    <!-- Admin Configuration Dialog -->
    <AdminConfigurationDialog
      v-model="showAdminConfig"
      @settings-saved="handleAdminConfigSaved"
    />

    <!-- Create User Dialog -->
    <v-dialog v-model="showCreateUserDialog" max-width="600">
      <v-card>
        <v-card-title class="text-h5">
          <v-icon left>mdi-account-plus</v-icon>
          Create User Account
        </v-card-title>
        <v-card-text>
          <v-alert type="info" variant="tonal" class="mb-4">
            <v-alert-title>Create Portal Account</v-alert-title>
            This will create a new user account in the MonacoUSA Portal with email verification.
          </v-alert>
          
          <v-form ref="createUserForm" v-model="createUserValid">
            <v-row>
              <v-col cols="6">
                <v-text-field
                  v-model="newUser.firstName"
                  label="First Name"
                  :rules="[v => !!v || 'First name is required']"
                  variant="outlined"
                  required
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model="newUser.lastName"
                  label="Last Name"
                  :rules="[v => !!v || 'Last name is required']"
                  variant="outlined"
                  required
                />
              </v-col>
            </v-row>

            <v-text-field
              v-model="newUser.email"
              label="Email Address"
              type="email"
              :rules="[
                v => !!v || 'Email is required',
                v => /.+@.+\..+/.test(v) || 'Email must be valid'
              ]"
              variant="outlined"
              required
            />

            <v-select
              v-model="newUser.role"
              label="User Role"
              :items="roleOptions"
              item-title="title"
              item-value="value"
              variant="outlined"
              required
            />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showCreateUserDialog = false">Cancel</v-btn>
          <v-btn 
            color="primary" 
            :loading="creatingUser"
            :disabled="!createUserValid"
            @click="createUserAccount"
          >
            Create Account
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </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 showCreateUserDialog = ref(false);
const showAdminConfig = ref(false);

// Create user dialog data
const createUserValid = ref(false);
const creatingUser = ref(false);
const newUser = ref({
  firstName: '',
  lastName: '',
  email: '',
  role: 'user'
});

const roleOptions = [
  { title: 'User', value: 'user' },
  { title: 'Board Member', value: 'board' },
  { title: 'Administrator', value: 'admin' }
];

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 handleAdminConfigSaved = () => {
  console.log('Admin configuration saved successfully');
  showAdminConfig.value = false;
};

const createUserAccount = async () => {
  if (!createUserValid.value) return;
  
  creatingUser.value = true;
  try {
    console.log('Creating user account:', newUser.value);
    
    // TODO: Implement actual user creation using enhanced Keycloak API
    // For now, just show success
    await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate API call
    
    // Reset form
    newUser.value = {
      firstName: '',
      lastName: '',
      email: '',
      role: 'user'
    };
    
    showCreateUserDialog.value = false;
    console.log('User account created successfully');
    
    // TODO: Show success notification
    // TODO: Refresh user list
  } catch (error) {
    console.error('Failed to create user account:', error);
    // TODO: Show error notification
  } finally {
    creatingUser.value = false;
  }
};

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>
