<template>
  <v-app>
    <v-navigation-drawer 
      v-model="drawer" 
      :rail="miniVariant"
      :expand-on-hover="false"
      permanent
      width="280"
      rail-width="100"
      class="enhanced-glass-drawer"
    >
      <!-- Enhanced Logo Section -->
      <v-list-item class="pa-4 text-center enhanced-glass-logo">
        <template v-if="!miniVariant">
          <v-img 
            src="/MONACOUSA-Flags_376x376.png" 
            width="80" 
            height="80"
            class="mx-auto mb-2 shimmer-animation" 
          />
          <div class="text-h6 font-weight-bold text-gradient">
            MonacoUSA Portal
          </div>
          <v-chip 
            size="x-small" 
            class="glass-badge mt-1"
          >
            ADMINISTRATOR
          </v-chip>
        </template>
        <template v-else>
          <v-img 
            src="/MONACOUSA-Flags_376x376.png" 
            width="40" 
            height="40"
            class="mx-auto shimmer-animation" 
          />
        </template>
      </v-list-item>
      
      <v-divider class="glass-divider mx-3" />
      
      <!-- Enhanced Navigation Menu -->
      <v-list nav density="comfortable" class="enhanced-glass-nav">
        <!-- Admin Overview -->
        <v-tooltip 
          :text="miniVariant ? 'Admin Dashboard' : ''"
          location="end"
          :disabled="!miniVariant"
        >
          <template v-slot:activator="{ props }">
            <v-list-item 
              v-bind="props"
              to="/admin/dashboard" 
              prepend-icon="mdi-view-dashboard"
              :title="!miniVariant ? 'Admin Dashboard' : undefined"
              value="dashboard"
              class="glass-nav-item animated-nav-item"
            />
          </template>
        </v-tooltip>

        <!-- User Management -->
        <v-list-group value="users" v-if="!miniVariant">
          <template v-slot:activator="{ props }">
            <v-list-item
              v-bind="props"
              prepend-icon="mdi-account-cog"
              title="User Management"
              class="glass-nav-item animated-nav-item"
            />
          </template>
          
          <v-list-item 
            to="/admin/users" 
            title="All Users"
            value="users-list"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/users/roles" 
            title="Roles & Permissions"
            value="roles"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            @click="openKeycloak" 
            title="Keycloak Admin"
            value="keycloak"
            class="glass-nav-item-sub"
          >
            <template v-slot:append>
              <v-icon size="small" class="monaco-red-text">mdi-open-in-new</v-icon>
            </template>
          </v-list-item>
        </v-list-group>

        <!-- Member Management -->
        <v-list-group value="members" v-if="!miniVariant">
          <template v-slot:activator="{ props }">
            <v-list-item
              v-bind="props"
              prepend-icon="mdi-account-group"
              title="Member Management"
              class="glass-nav-item animated-nav-item"
            />
          </template>
          
          <v-list-item 
            to="/admin/members" 
            title="All Members"
            value="members-list"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/members/import" 
            title="Import Members"
            value="import"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/members/export" 
            title="Export Data"
            value="export"
            class="glass-nav-item-sub"
          />
        </v-list-group>

        <!-- Financial Management -->
        <v-list-group value="financial" v-if="!miniVariant">
          <template v-slot:activator="{ props }">
            <v-list-item
              v-bind="props"
              prepend-icon="mdi-currency-usd"
              title="Financial"
              class="glass-nav-item animated-nav-item"
            />
          </template>
          
          <v-list-item 
            to="/admin/payments" 
            title="Payment Management"
            value="payments"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/payments/stripe" 
            title="Stripe Dashboard"
            value="stripe"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/payments/reports" 
            title="Financial Reports"
            value="financial-reports"
            class="glass-nav-item-sub"
          />
        </v-list-group>

        <!-- System Configuration -->
        <v-list-group value="system" v-if="!miniVariant">
          <template v-slot:activator="{ props }">
            <v-list-item
              v-bind="props"
              prepend-icon="mdi-cog"
              title="System"
              class="glass-nav-item animated-nav-item"
            />
          </template>
          
          <v-list-item 
            to="/admin/settings" 
            title="General Settings"
            value="settings"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/settings/email" 
            title="Email Configuration"
            value="email"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/settings/security" 
            title="Security Settings"
            value="security"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/logs" 
            title="System Logs"
            value="logs"
            class="glass-nav-item-sub"
          />
          <v-list-item 
            to="/admin/backup" 
            title="Backup & Restore"
            value="backup"
            class="glass-nav-item-sub"
          />
        </v-list-group>

        <!-- Events Management -->
        <v-tooltip 
          :text="miniVariant ? 'Events Management' : ''"
          location="end"
          :disabled="!miniVariant"
        >
          <template v-slot:activator="{ props }">
            <v-list-item 
              v-bind="props"
              to="/admin/events" 
              prepend-icon="mdi-calendar"
              :title="!miniVariant ? 'Events Management' : undefined"
              value="events"
              class="glass-nav-item animated-nav-item"
            />
          </template>
        </v-tooltip>

        <!-- Analytics -->
        <v-tooltip 
          :text="miniVariant ? 'Analytics & Insights' : ''"
          location="end"
          :disabled="!miniVariant"
        >
          <template v-slot:activator="{ props }">
            <v-list-item 
              v-bind="props"
              to="/admin/analytics" 
              prepend-icon="mdi-chart-line"
              :title="!miniVariant ? 'Analytics & Insights' : undefined"
              value="analytics"
              class="glass-nav-item animated-nav-item"
            />
          </template>
        </v-tooltip>

        <v-divider class="my-2 glass-divider" />
        
        <!-- Portal Access -->
        <v-list-subheader v-if="!miniVariant" class="monaco-subheader">Portal Access</v-list-subheader>
        <v-tooltip 
          :text="miniVariant ? 'Board Portal' : ''"
          location="end"
          :disabled="!miniVariant"
        >
          <template v-slot:activator="{ props }">
            <v-list-item 
              v-bind="props"
              to="/board/dashboard" 
              prepend-icon="mdi-shield-account"
              :title="!miniVariant ? 'Board Portal' : undefined"
              value="board-view"
              class="glass-nav-item animated-nav-item"
            />
          </template>
        </v-tooltip>
        <v-tooltip 
          :text="miniVariant ? 'Member Portal' : ''"
          location="end"
          :disabled="!miniVariant"
        >
          <template v-slot:activator="{ props }">
            <v-list-item 
              v-bind="props"
              to="/member/dashboard" 
              prepend-icon="mdi-account"
              :title="!miniVariant ? 'Member Portal' : undefined"
              value="member-view"
              class="glass-nav-item animated-nav-item"
            />
          </template>
        </v-tooltip>
      </v-list>
      
      <!-- Enhanced Profile Card -->
      <template v-slot:append>
        <div class="pa-2">
          <v-card class="glass-profile-card overflow-visible">
            <div class="d-flex align-center" :class="miniVariant ? 'flex-column py-3 px-2' : 'pa-3'">
              <!-- Avatar Section -->
              <ProfileAvatar
                :member-id="memberData?.member_id || memberData?.Id"
                :first-name="memberData?.first_name || user?.firstName"
                :last-name="memberData?.last_name || user?.lastName"
                :member-name="memberData?.FullName || user?.name"
                :size="miniVariant ? '32' : 'small'"
                :class="miniVariant ? '' : 'mr-3'"
              />
              
              <!-- Info Section (Hidden in mini mode) -->
              <div v-if="!miniVariant" class="flex-grow-1">
                <div class="text-subtitle-2 font-weight-bold">{{ user?.name || 'Administrator' }}</div>
                <div class="text-caption text-medium-emphasis">{{ user?.email?.split('@')[0] || 'admin' }}</div>
                <v-chip size="x-small" class="mt-1 glass-badge">Admin</v-chip>
              </div>
              
              <!-- Action Buttons -->
              <div :class="miniVariant ? 'mt-2' : 'ml-auto'">
                <v-menu location="top" offset-y>
                  <template v-slot:activator="{ props }">
                    <v-btn 
                      v-bind="props"
                      icon
                      :size="miniVariant ? 'small' : 'small'"
                      variant="text"
                      class="profile-menu-btn"
                    >
                      <v-icon>mdi-dots-vertical</v-icon>
                    </v-btn>
                  </template>
                  <v-list density="compact" class="glass-menu" min-width="200">
                    <v-list-item @click="() => {}" class="hover-lift">
                      <template v-slot:prepend>
                        <v-icon size="small" color="primary">mdi-account-circle</v-icon>
                      </template>
                      <v-list-item-title>My Profile</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="() => {}" class="hover-lift">
                      <template v-slot:prepend>
                        <v-icon size="small" color="info">mdi-cog-outline</v-icon>
                      </template>
                      <v-list-item-title>Settings</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="() => {}" class="hover-lift">
                      <template v-slot:prepend>
                        <v-icon size="small" color="warning">mdi-bell-outline</v-icon>
                      </template>
                      <v-list-item-title>Notifications</v-list-item-title>
                    </v-list-item>
                    <v-divider class="my-1 glass-divider" />
                    <v-list-item @click="logout" class="hover-lift">
                      <template v-slot:prepend>
                        <v-icon size="small" color="error">mdi-logout-variant</v-icon>
                      </template>
                      <v-list-item-title class="text-error">Sign Out</v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>
              </div>
            </div>
          </v-card>
        </div>
      </template>
    </v-navigation-drawer>
    
    <v-app-bar elevation="0" flat class="glass-app-bar admin-bar">
      <v-btn
        icon
        @click="toggleDrawer"
        class="glass-icon-btn mr-2"
      >
        <v-icon>{{ miniVariant ? 'mdi-menu' : 'mdi-menu-open' }}</v-icon>
      </v-btn>
      
      <v-toolbar-title class="font-weight-bold d-flex align-center text-white">
        Admin Portal
        <v-chip 
          size="x-small" 
          class="ml-2 glass-chip"
        >
          FULL ACCESS
        </v-chip>
      </v-toolbar-title>
      
      <v-spacer />

      <!-- System Status Indicator with Glass Effect -->
      <v-chip
        :color="systemStatus === 'healthy' ? 'success' : 'warning'"
        variant="flat"
        size="small"
        class="mr-2 glass-chip"
      >
        <v-icon start size="small">
          {{ systemStatus === 'healthy' ? 'mdi-check-circle' : 'mdi-alert' }}
        </v-icon>
        System {{ systemStatus }}
      </v-chip>

      <!-- Quick Actions with Glass Effects -->
      <v-btn 
        icon 
        class="glass-icon-btn"
        @click="toggleCommandPalette"
      >
        <v-icon>mdi-console</v-icon>
      </v-btn>

      <v-btn icon class="glass-icon-btn">
        <v-badge 
          :content="alerts" 
          :value="alerts > 0"
          color="error"
        >
          <v-icon>mdi-bell-alert</v-icon>
        </v-badge>
      </v-btn>
      
      <!-- User Menu -->
      <v-menu offset-y>
        <template v-slot:activator="{ props }">
          <v-btn icon v-bind="props" class="glass-icon-btn">
            <ProfileAvatar 
              :member-id="memberData?.member_id"
              :member-name="user?.name"
              :first-name="user?.firstName || memberData?.first_name"
              :last-name="user?.lastName || memberData?.last_name"
              size="small"
              :lazy="false"
              show-border
            />
          </v-btn>
        </template>
        
        <v-list min-width="250" class="glass-dropdown">
          <v-list-item>
            <v-list-item-title class="font-weight-bold">
              {{ user?.name || 'Administrator' }}
            </v-list-item-title>
            <v-list-item-subtitle>
              {{ user?.email }}
            </v-list-item-subtitle>
          </v-list-item>
          
          <v-list-item>
            <v-chip 
              size="x-small" 
              class="monaco-chip-gradient"
            >
              ADMINISTRATOR
            </v-chip>
          </v-list-item>
          
          <v-divider class="my-2 glass-divider" />
          
          <v-list-item to="/admin/profile" class="glass-dropdown-item">
            <template v-slot:prepend>
              <v-icon>mdi-account</v-icon>
            </template>
            <v-list-item-title>Admin Profile</v-list-item-title>
          </v-list-item>
          
          <v-list-item to="/board/dashboard" class="glass-dropdown-item">
            <template v-slot:prepend>
              <v-icon>mdi-shield-account</v-icon>
            </template>
            <v-list-item-title>Board Portal</v-list-item-title>
          </v-list-item>
          
          <v-list-item to="/member/dashboard" class="glass-dropdown-item">
            <template v-slot:prepend>
              <v-icon>mdi-account-switch</v-icon>
            </template>
            <v-list-item-title>Member Portal</v-list-item-title>
          </v-list-item>
          
          <v-list-item to="/admin/settings" class="glass-dropdown-item">
            <template v-slot:prepend>
              <v-icon>mdi-cog</v-icon>
            </template>
            <v-list-item-title>System Settings</v-list-item-title>
          </v-list-item>
          
          <v-divider class="my-2 glass-divider" />
          
          <v-list-item @click="handleLogout" class="glass-dropdown-item text-error">
            <template v-slot:prepend>
              <v-icon color="error">mdi-logout</v-icon>
            </template>
            <v-list-item-title>Logout</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </v-app-bar>

    <!-- Command Palette Dialog with Glass Effect -->
    <v-dialog v-model="commandPaletteOpen" max-width="600">
      <v-card class="glass-card">
        <v-card-title class="d-flex align-center">
          <v-icon class="mr-2 monaco-red-text">mdi-console</v-icon>
          Admin Command Palette
          <v-spacer />
          <v-btn icon @click="commandPaletteOpen = false" class="glass-icon-btn">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>
        <v-card-text>
          <v-text-field
            v-model="commandQuery"
            label="Type a command..."
            prepend-inner-icon="mdi-chevron-right"
            variant="outlined"
            autofocus
            @keyup.enter="executeCommand"
            class="glass-input"
          />
          <div class="text-caption monaco-muted-text">
            Available commands: clear-cache, rebuild-index, sync-users, export-data
          </div>
        </v-card-text>
      </v-card>
    </v-dialog>
    
    <v-main class="glass-main">
      <v-container fluid class="pa-6">
        <!-- System Alerts Banner with Glass Effect -->
        <v-alert
          v-if="systemAlerts.length > 0"
          type="warning"
          variant="tonal"
          closable
          class="mb-4 glass-alert"
        >
          <v-alert-title>System Alerts</v-alert-title>
          <ul class="mt-2">
            <li v-for="alert in systemAlerts" :key="alert.id">
              {{ alert.message }}
            </li>
          </ul>
        </v-alert>
        
        <slot />
      </v-container>
    </v-main>
  </v-app>
</template>

<script setup lang="ts">
import type { Member } from '~/utils/types';
import ProfileAvatar from '~/components/ProfileAvatar.vue';

const { user, logout } = useAuth();
const drawer = ref(true);
const miniVariant = ref(false);
const alerts = ref(0);
const systemStatus = ref<'healthy' | 'warning' | 'error'>('healthy');
const systemAlerts = ref<Array<{ id: number; message: string }>>([]);
const commandPaletteOpen = ref(false);
const commandQuery = ref('');

// Fetch member data
const { data: sessionData } = await useFetch<{ success: boolean; member: Member | null }>('/api/auth/session', { 
  server: false
});

const memberData = computed<Member | null>(() => sessionData.value?.member || null);

// Load admin-specific data
onMounted(async () => {
  try {
    // Check system health
    const healthCheck = await $fetch('/api/admin/system/health');
    systemStatus.value = healthCheck?.data?.status || 'healthy';
    
    // Get critical alerts
    const alertsRes = await $fetch('/api/admin/alerts');
    alerts.value = alertsRes?.data?.count || 0;
    systemAlerts.value = alertsRes?.data?.alerts || [];
  } catch (error) {
    console.error('Error fetching admin data:', error);
    systemStatus.value = 'warning';
  }
});

const openKeycloak = () => {
  window.open('https://auth.monacousa.org/admin', '_blank');
};

const toggleDrawer = () => {
  miniVariant.value = !miniVariant.value;
};

const toggleCommandPalette = () => {
  commandPaletteOpen.value = true;
};

const executeCommand = async () => {
  if (commandQuery.value) {
    console.log('Executing command:', commandQuery.value);
    // Implement command execution logic
    commandPaletteOpen.value = false;
    commandQuery.value = '';
  }
};

const handleLogout = async () => {
  await logout();
};

// Responsive drawer behavior
const { width } = useDisplay();
watch(width, (newWidth) => {
  drawer.value = newWidth >= 1024;
}, { immediate: true });
</script>

<style scoped lang="scss">
@import '~/assets/scss/main.scss';

// Glass Drawer Styles
.glass-drawer {
  @include glass-effect(0.95, 30px);
  border-right: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.glass-logo-section {
  background: linear-gradient(135deg, 
    rgba(220, 38, 38, 0.05) 0%, 
    rgba(255, 255, 255, 0.8) 100%);
  border-radius: 16px;
  margin-bottom: 8px;
}

.float-animation {
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

// Monaco Text Colors
.monaco-red-text {
  color: #dc2626 !important;
}

.monaco-muted-text {
  color: #71717a;
}

// Glass Navigation Items
.glass-nav-list {
  background: transparent !important;
}

.glass-nav-item {
  border-radius: 12px !important;
  margin: 4px 12px !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  
  &:hover {
    background: rgba(220, 38, 38, 0.05) !important;
    transform: translateX(2px);
  }
  
  &.v-list-item--active {
    background: linear-gradient(135deg, 
      rgba(220, 38, 38, 0.15) 0%, 
      rgba(220, 38, 38, 0.08) 100%) !important;
    color: #dc2626 !important;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 3px;
      height: 70%;
      background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
      border-radius: 0 2px 2px 0;
    }
    
    .v-icon {
      color: #dc2626 !important;
    }
  }
}

.glass-nav-item-sub {
  padding-left: 52px !important;
  border-radius: 8px !important;
  margin: 2px 12px 2px 24px !important;
  transition: all 0.2s ease !important;
  
  &:hover {
    background: rgba(220, 38, 38, 0.03) !important;
  }
  
  &.v-list-item--active {
    background: rgba(220, 38, 38, 0.08) !important;
    color: #dc2626 !important;
  }
}

// Monaco Subheader
.monaco-subheader {
  color: #dc2626 !important;
  font-weight: 600;
  font-size: 0.75rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

// Glass Divider
.glass-divider {
  opacity: 0.2;
  border-color: rgba(220, 38, 38, 0.2);
}

// Admin App Bar with Gradient
.admin-bar {
  background: linear-gradient(135deg, 
    rgba(220, 38, 38, 0.95) 0%, 
    rgba(153, 27, 27, 0.95) 100%) !important;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

// Glass Icon Buttons
.glass-icon-btn {
  background: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(10px);
  color: white !important;
  transition: all 0.3s ease !important;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2) !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

// Glass Chips
.glass-chip {
  background: rgba(255, 255, 255, 0.2) !important;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white !important;
}

.monaco-chip-gradient {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%) !important;
  color: white !important;
  border: none;
  box-shadow: 0 2px 8px rgba(220, 38, 38, 0.25);
}

// Glass Dropdown
.glass-dropdown {
  @include glass-effect(0.95, 20px);
  border-radius: 12px !important;
  overflow: hidden;
}

.glass-dropdown-item {
  transition: all 0.2s ease !important;
  
  &:hover {
    background: rgba(220, 38, 38, 0.05) !important;
  }
}

// Glass Input
.glass-input {
  :deep(.v-field) {
    background: rgba(255, 255, 255, 0.5) !important;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(220, 38, 38, 0.2);
  }
}

// Glass Alert
.glass-alert {
  @include glass-effect(0.8, 15px);
  border: 1px solid rgba(245, 158, 11, 0.2) !important;
}

// Glass Main Background
.glass-main {
  background: linear-gradient(180deg, 
    rgba(250, 250, 250, 0.9) 0%, 
    rgba(245, 245, 245, 0.9) 100%);
  min-height: 100vh;
  position: relative;
  
  &::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: 
      radial-gradient(circle at 20% 50%, rgba(220, 38, 38, 0.03) 0%, transparent 50%),
      radial-gradient(circle at 80% 80%, rgba(220, 38, 38, 0.03) 0%, transparent 50%),
      radial-gradient(circle at 40% 20%, rgba(220, 38, 38, 0.03) 0%, transparent 50%);
    pointer-events: none;
    z-index: 0;
  }
}

// Responsive adjustments
@media (max-width: 1024px) {
  .glass-nav-item {
    margin: 2px 8px !important;
  }
  
  .glass-nav-item-sub {
    margin: 2px 8px 2px 16px !important;
  }
}
</style>