<template>
  <div class="cache-stats-view" :class="{ 'mobile-layout': isMobile }">
    <!-- US-608: Mobile Material Design Top Bar with Back Button -->
    <MobileTopBar
      v-if="isMobile"
      title="Statistici Cache"
      :show-back="true"
      :actions="mobileTopBarActions"
      @back-click="router.push('/settings')"
      @action-click="handleTopBarAction"
    />

    <!-- Desktop Header -->
    <div class="stats-header" v-if="!isMobile">
      <h1>Cache Statistics</h1>
      <div class="actions">
        <Button
          label="Clear Cache"
          icon="pi pi-trash"
          severity="danger"
          @click="showClearDialog = true"
          :loading="loading"
        />
        <Button
          label="Refresh"
          icon="pi pi-refresh"
          @click="loadStats"
          :loading="loading"
        />
      </div>
    </div>

    <Message v-if="error" severity="error" :closable="true" @close="clearError">
      {{ error }}
    </Message>

    <div v-if="!loading && stats" class="stats-grid">
      <!-- Cache Status -->
      <Card class="status-card">
        <template #title>Cache Status</template>
        <template #content>
          <div class="status-content">
            <div class="status-item">
              <label>Global Status:</label>
              <Tag
                :value="stats.global_enabled ? 'ENABLED' : 'DISABLED'"
                :severity="stats.global_enabled ? 'success' : 'danger'"
              />
            </div>
            <div class="status-item">
              <label>Your Setting:</label>
              <InputSwitch
                v-model="userCacheEnabled"
                @change="toggleUserCache"
              />
              <span>{{ userCacheEnabled ? "ON" : "OFF" }}</span>
            </div>
            <div class="status-item">
              <label>Auto-Invalidation:</label>
              <Tag
                :value="stats.auto_invalidate ? 'ENABLED' : 'DISABLED'"
                :severity="stats.auto_invalidate ? 'success' : 'warning'"
              />
            </div>
          </div>
        </template>
      </Card>

      <!-- Performance Metrics -->
      <Card class="metrics-card">
        <template #title>Performance Metrics</template>
        <template #content>
          <div class="hit-rate">
            <h3>Hit Rate: {{ stats.hit_rate?.toFixed(1) }}%</h3>
            <p>
              {{ stats.total_hits }} hits /
              {{ stats.total_hits + stats.total_misses }} total requests
            </p>
            <ProgressBar :value="stats.hit_rate" />
          </div>
        </template>
      </Card>

      <!-- Queries Saved -->
      <Card class="queries-card">
        <template #title>Queries Saved</template>
        <template #content>
          <ul class="queries-list">
            <li>
              Today:
              <strong>{{
                stats.queries_saved?.today?.toLocaleString()
              }}</strong>
              queries avoided
            </li>
            <li>
              This week:
              <strong>{{ stats.queries_saved?.week?.toLocaleString() }}</strong>
              queries avoided
            </li>
            <li>
              All time:
              <strong>{{
                stats.queries_saved?.total?.toLocaleString()
              }}</strong>
              queries avoided
            </li>
          </ul>
        </template>
      </Card>

      <!-- Response Times -->
      <Card class="response-times-card">
        <template #title>Response Time Comparison</template>
        <template #content>
          <DataTable :value="responseTimesTable" class="p-datatable-sm">
            <Column field="endpoint" header="Endpoint" />
            <Column field="cached" header="With Cache">
              <template #body="{ data }">{{ data.cached }} ms</template>
            </Column>
            <Column field="oracle" header="Without Cache">
              <template #body="{ data }">{{ data.oracle }} ms</template>
            </Column>
            <Column field="improvement" header="Improvement">
              <template #body="{ data }">
                <Tag :value="`${data.improvement}% ↓`" severity="success" />
              </template>
            </Column>
          </DataTable>
          <div v-if="overallAvg" class="average-row">
            <strong>Overall Average:</strong>
            {{ overallAvg.cached }} ms vs {{ overallAvg.oracle }} ms ({{
              overallAvg.improvement
            }}% faster)
          </div>
        </template>
      </Card>

      <!-- Cache Details -->
      <Card class="details-card">
        <template #title>Cache Details</template>
        <template #content>
          <ul class="details-list">
            <li>
              Memory entries:
              <strong>{{ stats.cache_size?.memory?.toLocaleString() }}</strong>
            </li>
            <li>
              SQLite entries:
              <strong>{{ stats.cache_size?.sqlite?.toLocaleString() }}</strong>
            </li>
            <li>
              Cache type: <strong>{{ stats.cache_type }}</strong>
            </li>
          </ul>
        </template>
      </Card>
    </div>

    <!-- Clear Cache Dialog -->
    <Dialog
      v-model:visible="showClearDialog"
      header="Clear Cache"
      :modal="true"
      :style="{ width: '450px' }"
    >
      <p>Are you sure you want to clear the cache?</p>
      <div class="clear-options">
        <div class="p-field-radiobutton">
          <RadioButton id="clear_all" v-model="clearScope" value="all" />
          <label for="clear_all">All companies</label>
        </div>
        <div class="p-field-radiobutton">
          <RadioButton
            id="clear_current"
            v-model="clearScope"
            value="current"
          />
          <label for="clear_current">Current company only</label>
        </div>
      </div>
      <template #footer>
        <Button label="Cancel" text @click="showClearDialog = false" />
        <Button
          label="Clear"
          severity="danger"
          @click="clearCache"
          :loading="loading"
        />
      </template>
    </Dialog>

    <!-- US-111/US-307: Mobile Bottom Navigation (using default nav items) -->
    <MobileBottomNav v-if="isMobile" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useCacheStore } from "@reports/stores/cacheStore";
import { useCompanyStore, useAuthStore, useAccountingPeriodStore } from "@reports/stores/sharedStores";
import { useToast } from "primevue/usetoast";
import Button from "primevue/button";
import Card from "primevue/card";
import DataTable from "primevue/datatable";
import Column from "primevue/column";
import Tag from "primevue/tag";
import ProgressBar from "primevue/progressbar";
import InputSwitch from "primevue/inputswitch";
import Dialog from "primevue/dialog";
import RadioButton from "primevue/radiobutton";
import Message from "primevue/message";
// US-111/US-608: Mobile Material Design components
import MobileTopBar from "@shared/components/mobile/MobileTopBar.vue";
import MobileBottomNav from "@shared/components/mobile/MobileBottomNav.vue";
import { useRouter } from "vue-router";

const router = useRouter();
const cacheStore = useCacheStore();
const companyStore = useCompanyStore();
const periodStore = useAccountingPeriodStore();
const toast = useToast();
const authStore = useAuthStore();

const loading = computed(() => cacheStore.isLoading);
const error = computed(() => cacheStore.error);
const stats = computed(() => cacheStore.stats);

const userCacheEnabled = ref(true);
const showClearDialog = ref(false);
const clearScope = ref("current");

// US-111/US-608: Mobile state
const isMobile = ref(window.innerWidth <= 768);

// US-111: Mobile TopBar actions (refresh only for cache stats)
const mobileTopBarActions = computed(() => [
  {
    icon: "pi pi-refresh",
    label: "Actualizează",
    tooltip: "Actualizează statistici",
  },
]);

// US-111: Handle top bar action clicks
const handleTopBarAction = (action) => {
  if (action.icon === "pi pi-refresh") {
    loadStats();
  }
};

// US-307: Removed custom mobileBottomNavItems - using MobileBottomNav defaults

// US-111: Handle window resize
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768;
};

const responseTimesTable = computed(() => {
  if (!stats.value?.response_times) return [];

  return Object.entries(stats.value.response_times).map(([key, data]) => ({
    endpoint: formatEndpointName(key),
    cached: data.cached,
    oracle: data.oracle,
    improvement: data.improvement,
  }));
});

const overallAvg = computed(() => {
  const times = Object.values(stats.value?.response_times || {});
  if (times.length === 0) return null;

  const avgCached = times.reduce((sum, t) => sum + t.cached, 0) / times.length;
  const avgOracle = times.reduce((sum, t) => sum + t.oracle, 0) / times.length;
  const improvement = (((avgOracle - avgCached) / avgOracle) * 100).toFixed(0);

  return {
    cached: avgCached.toFixed(0),
    oracle: avgOracle.toFixed(0),
    improvement,
  };
});

async function loadStats() {
  try {
    await cacheStore.getStats();
    userCacheEnabled.value = stats.value?.user_enabled ?? true;
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Error",
      detail: "Failed to load cache statistics",
      life: 3000,
    });
  }
}

async function toggleUserCache() {
  try {
    await cacheStore.toggleUserCache(userCacheEnabled.value);
    toast.add({
      severity: "success",
      summary: "Success",
      detail: `Cache ${userCacheEnabled.value ? "enabled" : "disabled"} for you`,
      life: 3000,
    });
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Error",
      detail: "Failed to toggle cache",
      life: 3000,
    });
    // Revert toggle
    userCacheEnabled.value = !userCacheEnabled.value;
  }
}

async function clearCache() {
  try {
    const companyId =
      clearScope.value === "current"
        ? companyStore.currentCompany?.id_firma
        : null;
    await cacheStore.invalidateCache(companyId, null);

    toast.add({
      severity: "success",
      summary: "Success",
      detail: "Cache cleared successfully",
      life: 3000,
    });

    showClearDialog.value = false;
    await loadStats();
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Error",
      detail: "Failed to clear cache",
      life: 3000,
    });
  }
}

function formatEndpointName(key) {
  const names = {
    schema: "Schema Lookup",
    dashboard_summary: "Dashboard",
    dashboard_trends: "Dashboard Trends",
    companies: "Companies List",
    invoices: "Invoices",
    treasury: "Treasury",
  };
  return names[key] || key;
}

function clearError() {
  cacheStore.clearError();
}

onMounted(() => {
  // US-111: Add resize listener for mobile detection
  window.addEventListener("resize", handleResize);
  loadStats();
});

onUnmounted(() => {
  // US-111: Remove resize listener
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
/* Container - Uses global .app-container pattern */
.cache-stats-view {
  padding: var(--space-xl);
  max-width: 1400px;
  margin: 0 auto;
}

/* Header - Uses global .page-header pattern */
/* US-514: Reduced from var(--space-xl) to var(--space-md) for less excessive top spacing */
.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-md);
}

.stats-header h1 {
  margin: 0;
  color: var(--text-color);
}

.actions {
  display: flex;
  gap: var(--space-sm);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: var(--space-lg);
}

.status-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
}

.status-item {
  display: flex;
  align-items: center;
  gap: var(--space-md);
}

.status-item label {
  font-weight: var(--font-semibold);
  min-width: 140px;
}

/* Hit Rate - Uses global metric patterns */
.hit-rate {
  text-align: center;
}

.hit-rate h3 {
  margin: 0 0 var(--space-sm) 0;
  color: var(--primary-color);
}

.hit-rate p {
  margin: 0 0 var(--space-md) 0;
  color: var(--text-color-secondary);
  font-size: var(--text-sm);
}

.queries-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.queries-list li {
  padding: var(--space-sm) 0;
  border-bottom: 1px solid var(--surface-border);
}

.queries-list li:last-child {
  border-bottom: none;
}

.average-row {
  margin-top: var(--space-md);
  padding-top: var(--space-md);
  border-top: 2px solid var(--surface-border);
  text-align: center;
}

.details-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.details-list li {
  padding: var(--space-sm) 0;
  display: flex;
  justify-content: space-between;
}

.clear-options {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
  margin-top: var(--space-md);
}

.p-field-radiobutton {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
}

.response-times-card {
  grid-column: 1 / -1;
}

/* ================================================
   US-111: Mobile Layout Styles
   ================================================ */

.mobile-layout {
  padding: 0;
  padding-top: 56px; /* MobileTopBar height */
  padding-bottom: 56px; /* MobileBottomNav height */
}

.mobile-layout .stats-grid {
  padding: var(--space-sm);
  gap: var(--space-sm);
  grid-template-columns: 1fr;
}

/* Mobile sidebar styles */
.mobile-sidebar .sidebar-header {
  padding: var(--space-md);
  border-bottom: 1px solid var(--surface-border);
}

.mobile-sidebar .sidebar-title {
  font-size: var(--text-lg);
  font-weight: var(--font-bold);
  color: var(--color-primary);
}

.mobile-sidebar .sidebar-menu {
  padding: var(--space-sm) 0;
}

.mobile-sidebar .sidebar-item {
  display: flex;
  align-items: center;
  gap: var(--space-md);
  padding: var(--space-md) var(--space-lg);
  color: var(--text-color);
  text-decoration: none;
  transition: background-color var(--transition-fast);
}

.mobile-sidebar .sidebar-item:hover,
.mobile-sidebar .sidebar-item:active {
  background: var(--surface-hover);
}

.mobile-sidebar .sidebar-item.active {
  background: var(--blue-50);
  color: var(--color-primary);
}

.mobile-sidebar .sidebar-item i {
  font-size: var(--text-xl);
  width: 24px;
  text-align: center;
}

/* ================================================
   Dark Mode Support for Mobile
   ================================================ */

[data-theme="dark"] .mobile-sidebar .sidebar-item.active {
  background: var(--blue-900);
  color: var(--blue-400);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .mobile-sidebar .sidebar-item.active {
    background: var(--blue-900);
    color: var(--blue-400);
  }
}

/* Responsive - Cache stats specific adjustments */
@media (max-width: 768px) {
  .stats-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--space-md);
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
