<script setup lang="ts">
import type {
  KnowledgeBaseCreateInput,
  KnowledgeBaseListItem,
  ModelListItem,
} from '#/api/ai-platform/ai-platform';

import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';
import {
  CircleHelp,
  Database,
  Edit,
  MoreVertical,
  Plus,
  Trash2,
} from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElEmpty,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElSwitch,
  ElTag,
  ElTooltip,
} from 'element-plus';

import {
  createKnowledgeBaseApi,
  deleteKnowledgeBaseApi,
  getActiveModelsApi,
  getKnowledgeBaseListApi,
  updateKnowledgeBaseApi,
} from '#/api/ai-platform/ai-platform';
import { ZqDialog } from '#/components/zq-dialog';
import { useAppContextStore } from '#/store/app-context';

defineOptions({ name: 'KnowledgeBase' });

const router = useRouter();
const appContextStore = useAppContextStore();

const isMainApp = !appContextStore.currentApp?.id;

// 表单
const createForm = reactive<KnowledgeBaseCreateInput & { id?: string }>({
  name: '',
  code: '',
  description: '',
  embedding_model_id: undefined,
  embedding_dimensions: 1536,
  chunk_strategy: 'auto',
  chunk_size: 500,
  chunk_overlap: 50,
  retrieval_mode: 'hybrid',
  top_k: 5,
  score_threshold: 0.5,
  indexing_technique: 'high_quality',
  is_global: false,
});

const formRef = ref();
const isEditMode = ref(false);
const formLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('');

// Embedding 模型列表
const embeddingModels = ref<ModelListItem[]>([]);

async function loadEmbeddingModels() {
  try {
    const res = await getActiveModelsApi();
    embeddingModels.value = res.filter((m) => m.model_type === 'embedding');
  } catch {
    // ignore
  }
}

// 列表
const searchKeyword = ref('');
const loading = ref(false);
const kbList = ref<KnowledgeBaseListItem[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 12,
  total: 0,
});

async function fetchList() {
  loading.value = true;
  try {
    const res = await getKnowledgeBaseListApi({
      page: pagination.current,
      pageSize: pagination.pageSize,
      name: searchKeyword.value || undefined,
      applicationId: appContextStore.currentApp?.id,
    });
    kbList.value = res.items;
    pagination.total = res.total;
  } catch (error) {
    console.error('Failed to load knowledge base list:', error);
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  pagination.current = 1;
  fetchList();
}

function handlePageChange(page: number) {
  pagination.current = page;
  fetchList();
}

function handleSizeChange(size: number) {
  pagination.pageSize = size;
  pagination.current = 1;
  fetchList();
}

function handleCreate() {
  isEditMode.value = false;
  createForm.id = undefined;
  createForm.name = '';
  createForm.code = '';
  createForm.description = '';
  createForm.embedding_model_id = undefined;
  createForm.embedding_dimensions = 1536;
  createForm.chunk_strategy = 'auto';
  createForm.chunk_size = 500;
  createForm.chunk_overlap = 50;
  createForm.retrieval_mode = 'hybrid';
  createForm.top_k = 5;
  createForm.score_threshold = 0.5;
  createForm.indexing_technique = 'high_quality';
  createForm.is_global = false;
  dialogTitle.value = $t('ai-platform.knowledge.create');
  dialogVisible.value = true;
}

function handleEditInfo(item: KnowledgeBaseListItem) {
  isEditMode.value = true;
  createForm.id = item.id;
  createForm.name = item.name;
  createForm.code = item.code;
  createForm.description = item.description || '';
  createForm.is_global = item.is_global || false;
  dialogTitle.value = $t('ai-platform.knowledge.edit');
  dialogVisible.value = true;
}

async function handleConfirm() {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    formLoading.value = true;
    try {
      if (isEditMode.value && createForm.id) {
        await updateKnowledgeBaseApi(createForm.id, {
          name: createForm.name,
          description: createForm.description,
          is_global: createForm.is_global,
        });
        ElMessage.success($t('ai-platform.knowledge.saveSuccess'));
      } else {
        const res = await createKnowledgeBaseApi({
          application_id: appContextStore.currentApp?.id,
          is_global: createForm.is_global,
          name: createForm.name,
          code: createForm.code,
          description: createForm.description,
          embedding_model_id: createForm.embedding_model_id,
          embedding_dimensions: createForm.embedding_dimensions,
          chunk_strategy: createForm.chunk_strategy,
          chunk_size: createForm.chunk_size,
          chunk_overlap: createForm.chunk_overlap,
          retrieval_mode: createForm.retrieval_mode,
          top_k: createForm.top_k,
          score_threshold: createForm.score_threshold,
          indexing_technique: createForm.indexing_technique,
        });
        ElMessage.success($t('ai-platform.knowledge.createSuccess'));
        // 跳转到详情页
        router.push(
          appContextStore.getContextPath(
            `/ai-platform/knowledge-base/detail/${res.id}`,
          ),
        );
      }
      dialogVisible.value = false;
      fetchList();
    } catch {
      // error handled by interceptor
    } finally {
      formLoading.value = false;
    }
  });
}

function handleDetail(item: KnowledgeBaseListItem) {
  router.push(
    appContextStore.getContextPath(
      `/ai-platform/knowledge-base/detail/${item.id}`,
    ),
  );
}

async function handleDelete(item: KnowledgeBaseListItem) {
  try {
    await ElMessageBox.confirm(
      $t('ai-platform.knowledge.deleteConfirm'),
      $t('ai-platform.knowledge.delete'),
      { type: 'warning' },
    );
    await deleteKnowledgeBaseApi(item.id);
    ElMessage.success($t('ai-platform.knowledge.deleteSuccess'));
    fetchList();
  } catch {
    // cancelled
  }
}

function handleCommand(cmd: string, item: KnowledgeBaseListItem) {
  if (cmd === 'edit') {
    handleEditInfo(item);
  } else if (cmd === 'delete') {
    handleDelete(item);
  }
}

function getStatusType(status: string) {
  const map: Record<string, string> = {
    active: 'success',
    disabled: 'info',
  };
  return map[status] || 'info';
}

function getStatusText(status: string) {
  if (status === 'active') return $t('ai-platform.knowledge.active');
  if (status === 'disabled') return $t('ai-platform.knowledge.disabled');
  return status;
}

onMounted(() => {
  fetchList();
  loadEmbeddingModels();
});
</script>

<template>
  <div class="ai-knowledge-list-page">
    <Page auto-content-height v-loading="loading">
      <template #title>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-4">
            <ElInput
              v-model="searchKeyword"
              :placeholder="$t('ai-platform.knowledge.searchPlaceholder')"
              clearable
              class="w-64"
              @keyup.enter="handleSearch"
            />
            <ElButton @click="handleSearch">
              {{ $t('ai-platform.knowledge.search') }}
            </ElButton>
          </div>
          <ElButton type="primary" @click="handleCreate">
            <Plus class="mr-1 h-4 w-4" />
            {{ $t('ai-platform.knowledge.create') }}
          </ElButton>
        </div>
      </template>

      <!-- 卡片列表 -->
      <div
        v-if="kbList.length > 0"
        class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5"
      >
        <ElCard
          v-for="item in kbList"
          :key="item.id"
          class="cursor-pointer transition-shadow"
          shadow="hover"
          :body-style="{ padding: '0' }"
          style="border: none"
          @click="handleDetail(item)"
        >
          <div class="p-4">
            <!-- 头部 -->
            <div class="mb-4 flex gap-3">
              <div
                class="bg-primary/10 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg"
              >
                <Database class="text-primary h-5 w-5" />
              </div>
              <div class="min-w-0 flex-1">
                <div class="flex items-center justify-between">
                  <div class="min-w-0 flex-1 truncate text-sm font-medium">
                    {{ item.name }}
                  </div>
                  <div
                    class="flex flex-shrink-0 items-center -space-x-1"
                    @click.stop
                  >
                    <ElTooltip
                      :content="$t('ai-platform.knowledge.edit')"
                      placement="top"
                    >
                      <ElButton text size="small" @click="handleEditInfo(item)">
                        <Edit class="h-3.5 w-3.5" />
                      </ElButton>
                    </ElTooltip>
                    <ElTooltip
                      :content="$t('ai-platform.knowledge.delete')"
                      placement="top"
                    >
                      <ElButton text size="small" @click="handleDelete(item)">
                        <Trash2 class="h-3.5 w-3.5" />
                      </ElButton>
                    </ElTooltip>
                    <ElDropdown
                      trigger="click"
                      @command="(cmd: string) => handleCommand(cmd, item)"
                    >
                      <ElButton text size="small">
                        <MoreVertical class="h-3.5 w-3.5" />
                      </ElButton>
                      <template #dropdown>
                        <ElDropdownMenu>
                          <ElDropdownItem command="edit">
                            <Edit class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.knowledge.edit') }}
                          </ElDropdownItem>
                          <ElDropdownItem command="delete">
                            <Trash2 class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.knowledge.delete') }}
                          </ElDropdownItem>
                        </ElDropdownMenu>
                      </template>
                    </ElDropdown>
                  </div>
                </div>
                <div class="text-muted-foreground font-mono text-xs">
                  {{ item.code }}
                </div>
              </div>
            </div>

            <!-- 描述 -->
            <div
              class="text-muted-foreground mb-4 line-clamp-1 min-h-[18px] text-xs"
            >
              {{
                item.description || $t('ai-platform.knowledge.noDescription')
              }}
            </div>

            <!-- 标签 -->
            <div class="mb-4 flex items-center gap-1">
              <ElTag size="small" :type="getStatusType(item.status) as any">
                {{ getStatusText(item.status) }}
              </ElTag>
              <ElTag v-if="item.embedding_model_name" size="small">
                {{ item.embedding_model_name }}
              </ElTag>
            </div>

            <!-- 统计 + 时间 -->
            <div class="flex items-center justify-between">
              <div class="text-muted-foreground flex gap-3 text-xs">
                <span>
                  {{ $t('ai-platform.knowledge.documents') }}:
                  {{ item.document_count }}
                </span>
                <span>
                  {{ $t('ai-platform.knowledge.segments') }}:
                  {{ item.segment_count }}
                </span>
              </div>
              <span class="text-muted-foreground text-xs">
                {{ item.sys_create_datetime }}
              </span>
            </div>
          </div>
        </ElCard>
      </div>

      <!-- 空状态 -->
      <ElEmpty v-else :description="$t('common.noData')" />

      <!-- 分页 -->
      <template #footer>
        <div class="flex w-full items-center justify-end">
          <ElPagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[12, 24, 36, 48]"
            :pager-count="7"
            layout="total, sizes, prev, pager, next, jumper"
            background
            size="small"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </template>
    </Page>

    <!-- 创建/编辑弹窗 -->
    <ZqDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :confirm-loading="formLoading"
      width="560px"
      @confirm="handleConfirm"
    >
      <ElForm
        ref="formRef"
        :model="createForm"
        label-position="top"
        :rules="{
          name: [
            {
              required: true,
              message: $t('ai-platform.knowledge.namePlaceholder'),
              trigger: 'blur',
            },
          ],
          code: [
            {
              required: true,
              message: $t('ai-platform.knowledge.codePlaceholder'),
              trigger: 'blur',
            },
          ],
        }"
      >
        <ElFormItem :label="$t('ai-platform.knowledge.name')" prop="name">
          <ElInput
            v-model="createForm.name"
            :placeholder="$t('ai-platform.knowledge.namePlaceholder')"
          />
        </ElFormItem>
        <ElFormItem
          v-if="!isEditMode"
          :label="$t('ai-platform.knowledge.code')"
          prop="code"
        >
          <ElInput
            v-model="createForm.code"
            :placeholder="$t('ai-platform.knowledge.codePlaceholder')"
          />
        </ElFormItem>
        <ElFormItem :label="$t('ai-platform.knowledge.description')">
          <ElInput
            v-model="createForm.description"
            type="textarea"
            :placeholder="$t('ai-platform.knowledge.descriptionPlaceholder')"
            :rows="3"
          />
        </ElFormItem>

        <!-- 创建模式下显示更多配置 -->
        <template v-if="!isEditMode">
          <ElFormItem>
            <template #label>
              <div class="flex items-center gap-1">
                <span>{{ $t('ai-platform.knowledge.embeddingModel') }}</span>
                <ElTooltip
                  placement="top"
                  :content="$t('ai-platform.knowledge.embeddingModelTooltip')"
                >
                  <CircleHelp
                    class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                  />
                </ElTooltip>
              </div>
            </template>
            <ElSelect
              v-model="createForm.embedding_model_id"
              :placeholder="
                $t('ai-platform.knowledge.embeddingModelPlaceholder')
              "
              style="width: 100%"
              clearable
            >
              <ElOption
                v-for="model in embeddingModels"
                :key="model.id"
                :label="model.display_name"
                :value="model.id"
              />
            </ElSelect>
          </ElFormItem>
          <div class="grid grid-cols-2 gap-4">
            <ElFormItem>
              <template #label>
                <div class="flex items-center gap-1">
                  <span>{{ $t('ai-platform.knowledge.chunkStrategy') }}</span>
                  <ElTooltip
                    placement="top"
                    :content="$t('ai-platform.knowledge.chunkStrategyTooltip')"
                  >
                    <CircleHelp
                      class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                    />
                  </ElTooltip>
                </div>
              </template>
              <ElSelect v-model="createForm.chunk_strategy" style="width: 100%">
                <ElOption
                  :label="$t('ai-platform.knowledge.chunkStrategies.auto')"
                  value="auto"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.chunkStrategies.recursive')"
                  value="recursive"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.chunkStrategies.markdown')"
                  value="markdown"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.chunkStrategies.fixed')"
                  value="fixed"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.chunkStrategies.sentence')"
                  value="sentence"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.chunkStrategies.qa')"
                  value="qa"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem>
              <template #label>
                <div class="flex items-center gap-1">
                  <span>{{
                    $t('ai-platform.knowledge.indexingTechnique')
                  }}</span>
                  <ElTooltip
                    placement="top"
                    :content="
                      $t('ai-platform.knowledge.indexingTechniqueTooltip')
                    "
                  >
                    <CircleHelp
                      class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                    />
                  </ElTooltip>
                </div>
              </template>
              <ElSelect
                v-model="createForm.indexing_technique"
                style="width: 100%"
              >
                <ElOption
                  :label="
                    $t('ai-platform.knowledge.indexingTechniques.high_quality')
                  "
                  value="high_quality"
                />
                <ElOption
                  :label="
                    $t('ai-platform.knowledge.indexingTechniques.economy')
                  "
                  value="economy"
                />
              </ElSelect>
            </ElFormItem>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <ElFormItem>
              <template #label>
                <div class="flex items-center gap-1">
                  <span>{{ $t('ai-platform.knowledge.retrievalMode') }}</span>
                  <ElTooltip
                    placement="top"
                    :content="$t('ai-platform.knowledge.retrievalModeTooltip')"
                  >
                    <CircleHelp
                      class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                    />
                  </ElTooltip>
                </div>
              </template>
              <ElSelect v-model="createForm.retrieval_mode" style="width: 100%">
                <ElOption
                  :label="$t('ai-platform.knowledge.retrievalModes.hybrid')"
                  value="hybrid"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.retrievalModes.vector')"
                  value="vector"
                />
                <ElOption
                  :label="$t('ai-platform.knowledge.retrievalModes.fulltext')"
                  value="fulltext"
                />
              </ElSelect>
            </ElFormItem>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <ElFormItem>
              <template #label>
                <div class="flex items-center gap-1">
                  <span>{{ $t('ai-platform.knowledge.chunkSize') }}</span>
                  <ElTooltip
                    placement="top"
                    :content="$t('ai-platform.knowledge.chunkSizeTooltip')"
                  >
                    <CircleHelp
                      class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                    />
                  </ElTooltip>
                </div>
              </template>
              <ElInputNumber
                v-model="createForm.chunk_size"
                :min="100"
                :max="4000"
                :step="100"
                style="width: 100%"
              />
            </ElFormItem>
            <ElFormItem>
              <template #label>
                <div class="flex items-center gap-1">
                  <span>{{ $t('ai-platform.knowledge.chunkOverlap') }}</span>
                  <ElTooltip
                    placement="top"
                    :content="$t('ai-platform.knowledge.chunkOverlapTooltip')"
                  >
                    <CircleHelp
                      class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                    />
                  </ElTooltip>
                </div>
              </template>
              <ElInputNumber
                v-model="createForm.chunk_overlap"
                :min="0"
                :max="500"
                :step="10"
                style="width: 100%"
              />
            </ElFormItem>
          </div>
        </template>

        <ElFormItem v-if="isMainApp">
          <template #label>
            <div class="flex items-center gap-1">
              <span>{{ $t('ai-platform.knowledge.globalVisible') }}</span>
              <ElTooltip
                placement="top"
                :content="$t('ai-platform.knowledge.globalVisibleTooltip')"
              >
                <CircleHelp
                  class="text-muted-foreground h-3.5 w-3.5 cursor-help"
                />
              </ElTooltip>
            </div>
          </template>
          <ElSwitch v-model="createForm.is_global" />
        </ElFormItem>
      </ElForm>
    </ZqDialog>
  </div>
</template>
