<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { configApi } from '../../services/configApi'
import { useUiStore } from '../../stores/ui'

const ui = useUiStore()
const loading = ref(true)
const data = ref<any>(null)

async function fetchOverview() {
  loading.value = true
  try {
    const res = await configApi.getConfigOverview()
    data.value = res.data
  } catch {
    ui.showToast('Failed to load overview', 'error')
  } finally {
    loading.value = false
  }
}

function formatBytes(bytes: number) {
  if (bytes === 0) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0) + ' ' + units[i]
}

function formatNumber(n: number | null) {
  if (n == null) return '—'
  return n.toLocaleString()
}

function formatDate(d: string | null) {
  if (!d) return 'Never'
  return new Date(d).toLocaleString()
}

function dbTypeLabel(t: string) {
  switch (t) {
    case 'sqlserver': return 'SQL Server'
    case 'hana': return 'SAP HANA'
    case 'postgresql': return 'PostgreSQL'
    case 'mysql': return 'MySQL'
    default: return t
  }
}

onMounted(fetchOverview)
</script>

<template>
  <div class="max-w-5xl">
    <div class="flex items-center justify-between mb-4">
      <h2 class="text-lg font-semibold">Configuration Overview</h2>
      <button @click="fetchOverview" :disabled="loading" class="btn-secondary text-xs">
        {{ loading ? 'Loading...' : 'Refresh' }}
      </button>
    </div>

    <div v-if="loading && !data" class="text-center py-12 text-dark-400">Loading overview...</div>

    <template v-else-if="data">
      <!-- Summary Cards -->
      <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
        <div class="card text-center">
          <div class="text-2xl font-bold">{{ data.registry.total_tables }}</div>
          <div class="text-xs text-dark-400 mt-1">Total Tables</div>
        </div>
        <div class="card text-center border-green-600/30">
          <div class="text-2xl font-bold text-green-400">{{ data.registry.synced_tables }}</div>
          <div class="text-xs text-dark-400 mt-1">Synced</div>
        </div>
        <div class="card text-center" :class="data.registry.unsynced_tables > 0 ? 'border-yellow-600/30' : ''">
          <div class="text-2xl font-bold" :class="data.registry.unsynced_tables > 0 ? 'text-yellow-400' : ''">
            {{ data.registry.unsynced_tables }}
          </div>
          <div class="text-xs text-dark-400 mt-1">Unsynced</div>
        </div>
        <div class="card text-center">
          <div class="text-2xl font-bold text-primary-400">{{ data.registry.scheduled_tables }}</div>
          <div class="text-xs text-dark-400 mt-1">Scheduled</div>
        </div>
        <div class="card text-center">
          <div class="text-2xl font-bold">{{ formatNumber(data.registry.total_rows) }}</div>
          <div class="text-xs text-dark-400 mt-1">Total Rows</div>
        </div>
      </div>

      <!-- Connections Table -->
      <div class="mb-6">
        <h3 class="text-sm font-medium text-dark-400 mb-2">Connections</h3>
        <div v-if="data.connections.length > 0" class="border border-dark-600 rounded overflow-hidden">
          <table class="w-full text-sm">
            <thead class="bg-dark-800">
              <tr>
                <th class="px-3 py-2 text-left text-dark-400 font-medium">Name</th>
                <th class="px-3 py-2 text-left text-dark-400 font-medium">Type</th>
                <th class="px-3 py-2 text-left text-dark-400 font-medium">Source</th>
                <th class="px-3 py-2 text-right text-dark-400 font-medium">Tables</th>
                <th class="px-3 py-2 text-right text-dark-400 font-medium">Synced</th>
                <th class="px-3 py-2 text-left text-dark-400 font-medium">Last Sync</th>
                <th class="px-3 py-2 text-center text-dark-400 font-medium">Active</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="c in data.connections" :key="c.id" class="border-t border-dark-700">
                <td class="px-3 py-1.5 font-medium">{{ c.name }}</td>
                <td class="px-3 py-1.5 text-dark-400">{{ dbTypeLabel(c.db_type) }}</td>
                <td class="px-3 py-1.5 text-dark-400">{{ c.source_system || '—' }}</td>
                <td class="px-3 py-1.5 text-right tabular-nums">{{ c.table_count }}</td>
                <td class="px-3 py-1.5 text-right tabular-nums text-green-400">{{ c.synced_count }}</td>
                <td class="px-3 py-1.5 text-dark-400 text-xs">{{ formatDate(c.last_sync_at) }}</td>
                <td class="px-3 py-1.5 text-center">
                  <span :class="c.is_active ? 'text-green-400' : 'text-dark-600'" class="text-xs font-bold">
                    {{ c.is_active ? 'ON' : 'OFF' }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <p v-else class="text-dark-500 text-sm">No connections configured.</p>
      </div>

      <!-- Local Storage -->
      <div class="mb-6">
        <h3 class="text-sm font-medium text-dark-400 mb-2">
          Local Storage (v3q_data)
          <span v-if="data.schema_totals.total_size_bytes > 0" class="text-dark-500 font-normal ml-2">
            {{ data.schema_totals.table_count }} tables, {{ formatBytes(data.schema_totals.total_size_bytes) }} total
          </span>
        </h3>
        <div v-if="data.local_tables.length > 0" class="border border-dark-600 rounded overflow-hidden">
          <div class="max-h-64 overflow-y-auto">
            <table class="w-full text-sm">
              <thead class="bg-dark-800 sticky top-0">
                <tr>
                  <th class="px-3 py-2 text-left text-dark-400 font-medium">Table</th>
                  <th class="px-3 py-2 text-right text-dark-400 font-medium">Est. Rows</th>
                  <th class="px-3 py-2 text-right text-dark-400 font-medium">Size</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="t in data.local_tables" :key="t.table_name" class="border-t border-dark-700">
                  <td class="px-3 py-1.5 font-mono text-xs">{{ t.table_name }}</td>
                  <td class="px-3 py-1.5 text-right tabular-nums text-dark-400">{{ formatNumber(t.row_estimate) }}</td>
                  <td class="px-3 py-1.5 text-right tabular-nums">{{ formatBytes(t.size_bytes) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <p v-else class="text-dark-500 text-sm">No tables synced to local storage yet.</p>
      </div>

      <!-- Unsynced Tables Warning -->
      <div v-if="data.unsynced_tables.length > 0" class="mb-6">
        <h3 class="text-sm font-medium text-yellow-400 mb-2">
          Unsynced Tables ({{ data.unsynced_tables.length }})
        </h3>
        <div class="border border-yellow-600/30 rounded overflow-hidden">
          <div class="max-h-48 overflow-y-auto">
            <table class="w-full text-sm">
              <thead class="bg-dark-800 sticky top-0">
                <tr>
                  <th class="px-3 py-2 text-left text-dark-400 font-medium">Table</th>
                  <th class="px-3 py-2 text-left text-dark-400 font-medium">Connection</th>
                  <th class="px-3 py-2 text-left text-dark-400 font-medium">Source</th>
                  <th class="px-3 py-2 text-right text-dark-400 font-medium">Rows</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="t in data.unsynced_tables" :key="t.id" class="border-t border-dark-700">
                  <td class="px-3 py-1.5 font-medium">{{ t.source_table }}</td>
                  <td class="px-3 py-1.5 text-dark-400">{{ t.connection_name || '—' }}</td>
                  <td class="px-3 py-1.5 text-dark-400 text-xs">{{ t.source_system || '—' }}</td>
                  <td class="px-3 py-1.5 text-right tabular-nums text-dark-400">{{ formatNumber(t.row_count) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="bg-dark-800 border-t border-yellow-600/30 px-3 py-2 text-xs text-dark-500">
            These tables are registered but have no data locally. Go to the Tables tab to sync them.
          </div>
        </div>
      </div>

      <!-- Last sync info -->
      <div v-if="data.registry.last_sync_time" class="text-xs text-dark-500">
        Last sync: {{ formatDate(data.registry.last_sync_time) }}
      </div>
    </template>
  </div>
</template>
