<template>
  <el-button @click="handleExport" :loading="exporting">{{ t('common.export') }}</el-button>
  <el-button @click="openImport">{{ t('common.import') }}</el-button>
  <input
    ref="fileInput"
    type="file"
    accept="application/json,.json"
    class="hidden-input"
    @change="onFileChange"
  />

  <el-dialog v-model="importVisible" :title="t('importExport.importTitle')" width="480px" destroy-on-close>
    <el-form label-width="100px">
      <el-form-item :label="t('importExport.importMode')">
        <el-select v-model="importMode">
          <el-option :label="t('importExport.upsert')" value="upsert" />
          <el-option :label="t('importExport.skip')" value="skip" />
          <el-option :label="t('importExport.create')" value="create" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('importExport.pending')">
        <span>{{ t('importExport.pendingCount', { n: pendingItems.length }) }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="importVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="importing" @click="confirmImport">{{ t('importExport.startImport') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { exportResource, importResource, parseImportFile } from '@/utils/importExport'

const { t } = useI18n()

const props = defineProps({
  resource: { type: String, required: true },
  exportFilename: { type: String, required: true },
})

const emit = defineEmits(['done'])

const exporting = ref(false)
const importing = ref(false)
const importVisible = ref(false)
const importMode = ref('upsert')
const pendingItems = ref([])
const fileInput = ref(null)

async function handleExport() {
  exporting.value = true
  try {
    const data = await exportResource(`/${props.resource}`, props.exportFilename)
    ElMessage.success(t('importExport.exportSuccess', { n: data.items?.length ?? 0 }))
  } catch (e) {
    ElMessage.error(e.response?.data?.error || t('message.exportFailed'))
  } finally {
    exporting.value = false
  }
}

function openImport() {
  fileInput.value?.click()
}

async function onFileChange(e) {
  const file = e.target.files?.[0]
  e.target.value = ''
  if (!file) return
  try {
    pendingItems.value = await parseImportFile(file)
    importMode.value = 'upsert'
    importVisible.value = true
  } catch (err) {
    ElMessage.error(err.message || t('importExport.parseFailed'))
  }
}

async function confirmImport() {
  importing.value = true
  try {
    const result = await importResource(`/${props.resource}`, importMode.value, pendingItems.value)
    const msg = t('importExport.importDone', {
      created: result.created,
      updated: result.updated,
      skipped: result.skipped,
      failed: result.failed,
    })
    if (result.failed > 0) {
      ElMessage.warning(msg)
      if (result.errors?.length) {
        console.warn('import errors:', result.errors)
      }
    } else {
      ElMessage.success(msg)
    }
    importVisible.value = false
    emit('done')
  } catch (e) {
    ElMessage.error(e.response?.data?.error || t('message.importFailed'))
  } finally {
    importing.value = false
  }
}
</script>
