<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';

import { EasyFlowFormModal } from '@easyflow/common-ui';
import { $t } from '@easyflow/locales';

import { InfoFilled } from '@element-plus/icons-vue';
import {
  ElButton,
  ElIcon,
  ElMessage,
  ElRadioButton,
  ElRadioGroup,
  ElTooltip,
} from 'element-plus';

import { api } from '#/api/request';
import ImportKnowledgeFileContainer from '#/views/ai/documentCollection/ImportKnowledgeFileContainer.vue';
import { buildKnowledgePath } from '#/views/ai/documentCollection/share-path';

const props = defineProps({
  requestClient: {
    type: Object as any,
    default: () => api,
  },
  endpointPrefix: {
    type: String,
    default: '',
  },
  knowledgeIdProp: {
    type: String,
    default: '',
  },
  enableBulkAuto: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['imported']);

const route = useRoute();
const fileUploadRef = ref<InstanceType<typeof ImportKnowledgeFileContainer>>();
const dialogVisible = ref(false);
const submitting = ref(false);
const batchReady = ref(false);
const duplicatePolicy = ref<'OVERWRITE' | 'REIMPORT' | 'SKIP'>('SKIP');

const knowledgeId = computed(
  () => props.knowledgeIdProp || (route.query.id as string) || '',
);

const resetDialogState = () => {
  batchReady.value = false;
  duplicatePolicy.value = 'SKIP';
  fileUploadRef.value?.reset?.();
};

const handleBatchStateChange = (state: { ready: boolean }) => {
  batchReady.value = state.ready;
};

const closeDialog = async () => {
  if (submitting.value) {
    return false;
  }
  try {
    if (props.enableBulkAuto) {
      await fileUploadRef.value?.cancelCurrentBatch?.();
    } else {
      resetDialogState();
    }
    dialogVisible.value = false;
    batchReady.value = false;
    duplicatePolicy.value = 'SKIP';
    return true;
  } catch (error: any) {
    ElMessage.error(
      error?.message || $t('documentCollection.importDoc.cancelBatchFailed'),
    );
    return false;
  }
};

const openDialog = () => {
  resetDialogState();
  dialogVisible.value = true;
};

const createTasks = async () => {
  const files = fileUploadRef.value?.getFilesData?.() || [];
  if (files.length === 0) {
    ElMessage.error($t('message.uploadFileFirst'));
    return;
  }

  submitting.value = true;
  let successCount = 0;
  let failedCount = 0;

  try {
    for (const file of files) {
      try {
        const res = await props.requestClient.post(
          buildKnowledgePath(
            props.endpointPrefix,
            '/api/v1/document/import/task/create',
          ),
          {
            knowledgeId: knowledgeId.value,
            fileName: file.fileName,
            filePath: file.filePath,
          },
        );
        if (res.errorCode === 0) {
          successCount += 1;
        } else {
          failedCount += 1;
        }
      } catch {
        failedCount += 1;
      }
    }

    if (successCount > 0) {
      ElMessage.success(
        failedCount > 0
          ? $t('documentCollection.importDoc.partialCreateSuccess')
          : $t('documentCollection.importDoc.createSuccess'),
      );
      dialogVisible.value = false;
      resetDialogState();
      emits('imported');
      return;
    }

    ElMessage.error($t('documentCollection.importDoc.importFailed'));
  } finally {
    submitting.value = false;
  }
};

const startBatchImport = async (importMode: 'AUTO' | 'MANUAL') => {
  const selectedBatchId = fileUploadRef.value?.getBatchId?.();
  if (!selectedBatchId || !fileUploadRef.value?.isBatchReady?.()) {
    ElMessage.error($t('documentCollection.importDoc.uploadCompleteFirst'));
    return;
  }
  submitting.value = true;
  try {
    const res = await props.requestClient.post(
      '/api/v1/document/import/batch/start',
      {
        batchId: selectedBatchId,
        duplicatePolicy: duplicatePolicy.value,
        importMode,
        knowledgeId: knowledgeId.value,
      },
    );
    if (res.errorCode !== 0) {
      return;
    }
    ElMessage.success(
      importMode === 'AUTO'
        ? $t('documentCollection.importDoc.autoImportStarted')
        : $t('documentCollection.importDoc.manualImportStarted'),
    );
    dialogVisible.value = false;
    resetDialogState();
    emits('imported');
  } finally {
    submitting.value = false;
  }
};

defineExpose({
  closeDialog,
  openDialog,
});
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :title="$t('button.importFile')"
    :before-close="closeDialog"
    :closable="!submitting"
    :centered="true"
    :confirm-loading="submitting"
    :confirm-text="$t('button.importFile')"
    :submitting="submitting"
    :show-footer="!enableBulkAuto"
    width="xl"
    @confirm="createTasks"
  >
    <div class="import-dialog">
      <p class="import-dialog__tip">
        {{
          $t(
            enableBulkAuto
              ? 'documentCollection.importDoc.batchUploadTip'
              : 'documentCollection.importDoc.uploadCreateTip',
          )
        }}
      </p>

      <ImportKnowledgeFileContainer
        ref="fileUploadRef"
        :batch-mode="enableBulkAuto"
        :knowledge-id="knowledgeId"
        @batch-state-change="handleBatchStateChange"
      />
      <div v-if="enableBulkAuto && batchReady" class="duplicate-policy">
        <span class="duplicate-policy__label">
          {{ $t('documentCollection.importDoc.duplicatePolicy') }}
        </span>
        <ElRadioGroup v-model="duplicatePolicy" size="small">
          <ElRadioButton value="SKIP">
            {{ $t('documentCollection.importDoc.skipDuplicates') }}
          </ElRadioButton>
          <ElRadioButton value="OVERWRITE">
            {{ $t('documentCollection.importDoc.overwriteDuplicates') }}
          </ElRadioButton>
          <ElRadioButton value="REIMPORT">
            {{ $t('documentCollection.importDoc.reimportDuplicates') }}
          </ElRadioButton>
        </ElRadioGroup>
      </div>
      <div v-if="enableBulkAuto" class="import-dialog__footer">
        <ElButton :disabled="submitting" @click="closeDialog">
          {{ $t('button.cancel') }}
        </ElButton>
        <ElButton
          :disabled="submitting || !batchReady"
          :loading="submitting"
          @click="startBatchImport('MANUAL')"
        >
          {{ $t('documentCollection.importDoc.manualImport') }}
        </ElButton>
        <ElTooltip
          :content="$t('documentCollection.importDoc.autoImportTip')"
          placement="top"
        >
          <ElButton
            type="primary"
            :disabled="submitting || !batchReady"
            :loading="submitting"
            @click="startBatchImport('AUTO')"
          >
            {{ $t('documentCollection.importDoc.autoImport') }}
            <ElIcon class="import-dialog__info"><InfoFilled /></ElIcon>
          </ElButton>
        </ElTooltip>
      </div>
    </div>
  </EasyFlowFormModal>
</template>

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

.import-dialog__tip {
  margin: 0;
  font-size: 14px;
  line-height: 22px;
  color: var(--el-text-color-secondary);
}

.import-dialog__footer {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.duplicate-policy {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 12px;
  align-items: center;
  min-height: 32px;
}

.duplicate-policy__label {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.import-dialog__footer :deep(.el-button + .el-button) {
  margin-left: 0;
}

.import-dialog__info {
  margin-left: 6px;
}

:deep(.upload-demo) {
  width: 100%;
}

:deep(.upload-demo .el-upload) {
  width: 100%;
}

:deep(.upload-demo .el-upload-dragger) {
  padding: 24px 20px;
  border-radius: 18px;
  box-shadow: none;
}

:deep(.upload-demo .el-icon) {
  margin-bottom: 8px;
}

:deep(.el-table) {
  --el-table-border-color: transparent;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table th.el-table__cell) {
  padding-top: 10px;
  padding-bottom: 10px;
  background: transparent;
}

:deep(.el-table td.el-table__cell) {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
