<template>
  <ElDialog
    :model-value="modelValue"
    :title="t('dictionary.import.title')"
    width="620px"
    destroy-on-close
    @close="handleClose"
  >
    <div class="import-body">
      <ElUpload
        drag
        :auto-upload="false"
        :limit="1"
        :file-list="fileList"
        accept=".csv,.json"
        :before-upload="handleBeforeUpload"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
      >
        <ElIcon class="el-icon--upload">
          <UploadFilled />
        </ElIcon>
        <div class="el-upload__text">{{ t('dictionary.import.dropHere') }}</div>
        <template #tip>
          <div class="el-upload__tip">{{ t('dictionary.import.tip') }}</div>
        </template>
      </ElUpload>

      <ElDivider />

      <ElForm label-width="140px">
        <ElFormItem :label="t('dictionary.import.conflictMode')">
          <ElRadioGroup v-model="conflictMode">
            <ElRadioButton :label="ConflictResolutionMode.Skip">
              {{ t('dictionary.import.skip') }}
            </ElRadioButton>
            <ElRadioButton :label="ConflictResolutionMode.Overwrite">
              {{ t('dictionary.import.overwrite') }}
            </ElRadioButton>
            <ElRadioButton :label="ConflictResolutionMode.Append">
              {{ t('dictionary.import.append') }}
            </ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>
      </ElForm>

      <ElProgress v-if="importing" :percentage="progress" status="success" />

      <div v-if="result" class="import-result">
        <ElAlert
          type="success"
          :closable="false"
          :title="
            t('dictionary.import.successSummary', {
              success: result.successCount,
              skip: result.skipCount,
              error: result.errorCount
            })
          "
        />
        <ElTable
          v-if="result.errors?.length"
          class="error-table"
          :data="result.errors"
          size="small"
        >
          <ElTableColumn prop="rowNumber" :label="t('dictionary.import.row')" width="80" />
          <ElTableColumn prop="field" :label="t('dictionary.import.field')" width="120" />
          <ElTableColumn prop="message" :label="t('dictionary.import.message')" min-width="200" />
        </ElTable>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">{{ t('dictionary.common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="importing" @click="handleImport">
          {{ t('dictionary.import.start') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import type { UploadFile, UploadUserFile } from 'element-plus'
  import { UploadFilled } from '@element-plus/icons-vue'
  import { importGroup } from '@/api/dictionary/group'
  import { ConflictResolutionMode } from '@/enums/Dictionary'

  defineOptions({ name: 'ImportDialog' })

  interface Props {
    modelValue: boolean
    group?: Api.Dictionary.DictionaryGroupDto | null
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    group: null
  })

  const emit = defineEmits<{
    (event: 'update:modelValue', value: boolean): void
    (event: 'success'): void
  }>()

  const fileList = ref<UploadUserFile[]>([])
  const selectedFile = ref<File | null>(null)
  const conflictMode = ref<ConflictResolutionMode>(ConflictResolutionMode.Skip)
  const importing = ref(false)
  const progress = ref(0)
  const result = ref<Api.Dictionary.DictionaryImportResultDto | null>(null)
  const { t } = useI18n()

  const fileFormat = computed<'csv' | 'json' | undefined>(() => {
    if (!selectedFile.value) return undefined
    const name = selectedFile.value.name.toLowerCase()
    if (name.endsWith('.csv')) return 'csv'
    if (name.endsWith('.json')) return 'json'
    return undefined
  })

  const handleBeforeUpload = (file: File) => {
    const maxSize = 10 * 1024 * 1024
    if (file.size > maxSize) {
      ElMessage.error(t('dictionary.import.fileTooLarge'))
      return false
    }
    return true
  }

  const handleFileChange = (file: UploadFile) => {
    selectedFile.value = file.raw ?? null
    fileList.value = file.raw ? [file as UploadUserFile] : []
    result.value = null
  }

  const handleFileRemove = () => {
    selectedFile.value = null
    fileList.value = []
    result.value = null
  }

  const handleClose = () => {
    emit('update:modelValue', false)
    handleFileRemove()
  }

  const handleImport = async () => {
    if (!props.group) {
      ElMessage.warning(t('dictionary.common.selectGroupFirst'))
      return
    }

    if (!selectedFile.value) {
      ElMessage.warning(t('dictionary.import.selectFile'))
      return
    }

    if (!fileFormat.value) {
      ElMessage.error(t('dictionary.import.unsupportedFormat'))
      return
    }

    importing.value = true
    progress.value = 0
    result.value = null

    try {
      progress.value = 30
      const response = await importGroup(props.group.id, {
        file: selectedFile.value,
        conflictMode: conflictMode.value,
        format: fileFormat.value
      })
      progress.value = 100
      result.value = response
      emit('success')
    } finally {
      importing.value = false
    }
  }
</script>

<style scoped>
  .import-body {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }

  .error-table {
    margin-top: 12px;
  }
</style>
