<script setup lang="ts">
import { ref } from 'vue'
import { useFileUpload } from '../../composables/useFileUpload'
import { useUiStore } from '../../stores/ui'

const emit = defineEmits<{ imported: [] }>()
const ui = useUiStore()
const { uploading, processing, progress, uploadFile, getSheets } = useFileUpload()

const selectedFile = ref<File | null>(null)
const sheets = ref<string[]>([])
const selectedSheet = ref('0')
const tableName = ref('')

async function handleFileSelect(e: Event) {
  const input = e.target as HTMLInputElement
  if (!input.files?.length) return
  selectedFile.value = input.files[0]

  // Auto-generate table name from filename
  const name = selectedFile.value.name
    .replace(/\.[^.]+$/, '')
    .replace(/[^\w]/g, '_')
    .toLowerCase()
  tableName.value = name

  // Get sheets if Excel
  if (name.match(/\.xlsx?$/i)) {
    try {
      sheets.value = await getSheets(selectedFile.value)
    } catch { /* CSV has no sheets */ }
  }
}

async function doImport() {
  if (!selectedFile.value || !tableName.value) return
  try {
    const result = await uploadFile(selectedFile.value, tableName.value, selectedSheet.value)
    ui.showToast(`Imported ${result.row_count} rows with ${result.column_count} columns`, 'success')
    emit('imported')
  } catch (e: any) {
    ui.showToast(e.response?.data?.detail || 'Import failed', 'error')
  }
}
</script>

<template>
  <div class="card mb-4 space-y-3">
    <h3 class="font-medium text-sm">Import Excel / CSV</h3>

    <input type="file" accept=".xlsx,.xls,.csv" @change="handleFileSelect" class="input-field text-sm" />

    <div v-if="selectedFile" class="space-y-3">
      <input v-model="tableName" placeholder="Table name in PostgreSQL" class="input-field" />

      <select v-if="sheets.length > 1" v-model="selectedSheet" class="input-field">
        <option v-for="(sheet, i) in sheets" :key="i" :value="sheet">{{ sheet }}</option>
      </select>

      <div v-if="uploading" class="space-y-1">
        <div class="w-full bg-dark-700 rounded-full h-2">
          <div class="bg-primary-500 h-2 rounded-full transition-all" :class="{ 'animate-pulse': processing }" :style="{ width: processing ? '100%' : progress + '%' }" />
        </div>
        <p v-if="processing" class="text-xs text-dark-400 animate-pulse">Processing: type inference, inserting rows, enriching columns...</p>
      </div>

      <button @click="doImport" :disabled="uploading || !tableName" class="btn-primary text-sm">
        {{ processing ? 'Processing...' : uploading ? `Uploading... ${progress}%` : 'Import File' }}
      </button>
    </div>
  </div>
</template>
