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

const ui = useUiStore()
const tables = ref<any[]>([])
const showUpload = ref(false)

async function fetchTables() {
  const { data } = await configApi.listTables()
  tables.value = data
}
onMounted(fetchTables)
</script>

<template>
  <div>
    <h2 class="text-lg font-semibold mb-4">Select Tables to Sync</h2>
    <p class="text-dark-400 text-sm mb-4">Choose which tables to sync from your databases, or import Excel/CSV files.</p>

    <button @click="showUpload = !showUpload" class="btn-secondary text-sm mb-4">
      {{ showUpload ? 'Hide' : 'Import Excel/CSV' }}
    </button>

    <ExcelUpload v-if="showUpload" @imported="showUpload = false; fetchTables()" />

    <div v-if="tables.length" class="space-y-2">
      <div v-for="t in tables" :key="t.id" class="flex items-center justify-between p-2 bg-dark-900 rounded text-sm">
        <div>
          <span>{{ t.display_name || t.source_table }}</span>
          <span class="text-dark-500 ml-2">({{ t.row_count?.toLocaleString() ?? '?' }} rows)</span>
        </div>
        <span :class="t.is_synced ? 'text-green-400' : 'text-dark-500'" class="text-xs">
          {{ t.is_synced ? 'Synced' : 'Not synced' }}
        </span>
      </div>
    </div>
    <p v-else class="text-dark-500 text-sm">No tables available. Connect a database and run discovery, or import files.</p>
  </div>
</template>
