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

import { $t } from '@easyflow/locales';

import { ElButton, ElCard, ElImage, ElTag } from 'element-plus';

import { knowledgeShareApi } from '#/api/knowledge-share';
import bookIcon from '#/assets/ai/knowledge/book.svg';
import ChunkDocumentTable from '#/views/ai/documentCollection/ChunkDocumentTable.vue';
import DocumentTable from '#/views/ai/documentCollection/DocumentTable.vue';
import FaqTable from '#/views/ai/documentCollection/FaqTable.vue';
import ImportKnowledgeDocFile from '#/views/ai/documentCollection/ImportKnowledgeDocFile.vue';
import KnowledgeSearch from '#/views/ai/documentCollection/KnowledgeSearch.vue';
import KnowledgeShareConfigPanel from '#/views/ai/documentCollection/KnowledgeShareConfigPanel.vue';
import SegmenterDoc from '#/views/ai/documentCollection/SegmenterDoc.vue';

interface KnowledgeShareViewDetail {
  knowledge?: Record<string, any>;
  permissionScopes?: string[];
}

const endpointPrefix = '/api/v1/share/knowledge';
const knowledgeInfo = ref<any>({});
const permissionScopes = ref<string[]>([]);
const loading = ref(false);
const selectedCategory = ref('');
const panelMode = ref<'chunk' | 'list' | 'process'>('list');
const documentId = ref('');
const documentTitle = ref('');
const documentTableRef = ref();
const importDocModalRef = ref<InstanceType<typeof ImportKnowledgeDocFile>>();

const isFaqCollection = computed(
  () => knowledgeInfo.value.collectionType === 'FAQ',
);
const collectionTypeLabel = computed(() =>
  isFaqCollection.value
    ? $t('documentCollection.collectionTypeFaq')
    : $t('documentCollection.collectionTypeDocument'),
);
const knowledgeTitle = computed(
  () =>
    knowledgeInfo.value.title ||
    knowledgeInfo.value.alias ||
    knowledgeInfo.value.englishName ||
    '',
);
const knowledgeDescription = computed(
  () => knowledgeInfo.value.description || '',
);
const permissionScopeSet = computed(
  () => new Set((permissionScopes.value || []).map((item) => String(item || '').toUpperCase())),
);
const canCreateContent = computed(() =>
  permissionScopeSet.value.has('CONTENT_CREATE'),
);
const canDeleteContent = computed(() =>
  permissionScopeSet.value.has('CONTENT_DELETE'),
);
const canUpdateContent = computed(() =>
  permissionScopeSet.value.has('CONTENT_UPDATE'),
);
const canUpdateConfig = computed(() =>
  permissionScopeSet.value.has('CONFIG_UPDATE'),
);
const canDownloadContent = computed(() =>
  permissionScopeSet.value.has('VIEW'),
);
const canManageContent = computed(
  () =>
    canCreateContent.value ||
    canDeleteContent.value ||
    canUpdateContent.value ||
    permissionScopeSet.value.has('IMPORT_EXPORT'),
);
const categoryData = computed(() => {
  if (isFaqCollection.value) {
    return [
      { key: 'faqList', name: $t('documentCollection.faq.faqList') },
      {
        key: 'knowledgeSearch',
        name: $t('documentCollection.knowledgeRetrieval'),
      },
      { key: 'config', name: $t('documentCollection.config') },
    ];
  }
  return [
    { key: 'documentList', name: $t('documentCollection.documentList') },
    {
      key: 'knowledgeSearch',
      name: $t('documentCollection.knowledgeRetrieval'),
    },
    { key: 'config', name: $t('documentCollection.config') },
  ];
});

const loadKnowledge = async () => {
  loading.value = true;
  try {
    const res = await knowledgeShareApi.get(
      `${endpointPrefix}/documentCollection/detail`,
    );
    const detail = (res.data || {}) as KnowledgeShareViewDetail;
    knowledgeInfo.value = detail.knowledge || {};
    permissionScopes.value = detail.permissionScopes || [];
    selectedCategory.value =
      knowledgeInfo.value.collectionType === 'FAQ' ? 'faqList' : 'documentList';
  } finally {
    loading.value = false;
  }
};

const handleViewDoc = (id: string) => {
  documentId.value = id;
  panelMode.value = 'chunk';
};

const backToDocumentList = () => {
  panelMode.value = 'list';
  documentTitle.value = '';
  documentTableRef.value?.reload?.();
};

const continueProcess = (doc: any) => {
  documentId.value = String(doc?.id || '');
  documentTitle.value = doc?.title || '';
  panelMode.value = 'process';
};

const openImport = () => {
  importDocModalRef.value?.openDialog?.();
};

const handleCategoryClick = (key: string) => {
  selectedCategory.value = key;
  panelMode.value = 'list';
};

onMounted(() => {
  loadKnowledge();
});
</script>

<template>
  <div class="share-page" v-loading="loading">
    <div class="share-shell">
      <ElCard shadow="never" class="share-hero">
        <div class="share-hero__main">
          <div class="share-hero__meta">
            <ElImage :src="bookIcon" class="share-hero__icon" />
            <div class="share-hero__text">
              <div class="share-hero__title-row">
                <div class="share-hero__title">{{ knowledgeTitle }}</div>
                <ElTag size="small" effect="plain" round>
                  {{ collectionTypeLabel }}
                </ElTag>
              </div>
              <div v-if="knowledgeDescription" class="share-hero__desc">
                {{ knowledgeDescription }}
              </div>
            </div>
          </div>
          <div class="share-hero__actions">
            <ElButton
              v-if="!isFaqCollection && canCreateContent"
              type="primary"
              @click="openImport"
            >
              {{ $t('button.importFile') }}
            </ElButton>
          </div>
        </div>
        <div class="share-tabs">
          <button
            v-for="item in categoryData"
            :key="item.key"
            class="share-tab"
            :class="{ 'is-active': selectedCategory === item.key }"
            @click="handleCategoryClick(item.key)"
          >
            {{ item.name }}
          </button>
        </div>
      </ElCard>

      <div class="share-body">
        <div v-if="selectedCategory === 'documentList'" class="share-panel">
          <DocumentTable
            v-if="panelMode === 'list'"
            ref="documentTableRef"
            :knowledge-id="knowledgeInfo.id"
            :permissions="{
              canCreateContent: canCreateContent,
              canDeleteContent: canDeleteContent,
              canDownloadContent: canDownloadContent,
            }"
            :request-client="knowledgeShareApi"
            :endpoint-prefix="endpointPrefix"
            @continue-process="continueProcess"
            @view-doc="handleViewDoc"
          />
          <ChunkDocumentTable
            v-else-if="panelMode === 'chunk'"
            :document-id="documentId"
            :manageable="canManageContent"
            :request-client="knowledgeShareApi"
            :endpoint-prefix="endpointPrefix"
          />
          <SegmenterDoc
            v-else-if="panelMode === 'process'"
            :knowledge-id="String(knowledgeInfo.id || '')"
            :document-id="documentId"
            :document-title="documentTitle"
            :request-client="knowledgeShareApi"
            :endpoint-prefix="endpointPrefix"
            @cancel="backToDocumentList"
            @started="backToDocumentList"
          />
          <div v-if="panelMode === 'chunk'" class="share-panel__footer">
            <ElButton @click="backToDocumentList">
              {{ $t('button.back') }}
            </ElButton>
          </div>
        </div>

        <div v-if="selectedCategory === 'faqList'" class="share-panel">
          <FaqTable
            :knowledge-id="knowledgeInfo.id"
            :manageable="canManageContent"
            :request-client="knowledgeShareApi"
            :endpoint-prefix="endpointPrefix"
          />
        </div>

        <div v-if="selectedCategory === 'knowledgeSearch'" class="share-search">
          <KnowledgeSearch
            :knowledge-id="knowledgeInfo.id"
            :request-client="knowledgeShareApi"
            :endpoint-prefix="endpointPrefix"
          />
        </div>

        <div v-if="selectedCategory === 'config'" class="share-config">
          <KnowledgeShareConfigPanel
            :knowledge-id="String(knowledgeInfo.id || '')"
            :detail-data="knowledgeInfo"
            :manageable="canUpdateConfig"
            :request-client="knowledgeShareApi"
            :endpoint-prefix="endpointPrefix"
            @reload="loadKnowledge"
          />
        </div>
      </div>
    </div>

    <ImportKnowledgeDocFile
      ref="importDocModalRef"
      :request-client="knowledgeShareApi"
      :endpoint-prefix="endpointPrefix"
      :knowledge-id-prop="String(knowledgeInfo.id || '')"
      @imported="backToDocumentList"
    />
  </div>
</template>

<style scoped>
.share-page {
  min-height: 100vh;
  padding: 32px 20px;
  background:
    radial-gradient(
      circle at top left,
      rgb(232 242 255 / 90%),
      transparent 32%
    ),
    linear-gradient(180deg, #f6f9fc 0%, #f2f5f9 100%);
}

.share-shell {
  display: grid;
  gap: 20px;
  max-width: 1280px;
  margin: 0 auto;
}

.share-hero {
  border-radius: 20px;
}

.share-hero__main {
  display: flex;
  gap: 16px;
  align-items: center;
  justify-content: space-between;
}

.share-hero__meta {
  display: flex;
  gap: 16px;
  align-items: center;
}

.share-hero__text {
  display: grid;
  gap: 8px;
}

.share-hero__icon {
  width: 44px;
  height: 44px;
}

.share-hero__title-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.share-hero__title {
  font-size: 28px;
  font-weight: 700;
  letter-spacing: -0.02em;
}

.share-hero__desc {
  margin-top: 6px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.share-tabs {
  display: flex;
  gap: 12px;
  margin-top: 18px;
}

.share-tab {
  padding: 10px 16px;
  color: var(--el-text-color-regular);
  background: transparent;
  border: 1px solid transparent;
  border-radius: 999px;
  transition: all 0.2s ease;
}

.share-tab.is-active {
  color: var(--el-color-primary);
  background: rgb(64 158 255 / 8%);
  border-color: rgb(64 158 255 / 18%);
}

.share-body,
.share-panel,
.share-search,
.share-config {
  min-height: 640px;
}

.share-panel__footer {
  padding: 16px 20px 20px;
}

@media (max-width: 768px) {
  .share-page {
    padding: 16px 12px;
  }

  .share-hero__main {
    flex-direction: column;
    align-items: flex-start;
  }

  .share-hero__meta {
    align-items: flex-start;
  }

  .share-hero__eyebrow {
    flex-wrap: wrap;
  }

  .share-tabs {
    flex-wrap: wrap;
  }

  .share-hero__title {
    font-size: 24px;
  }
}
</style>
