<template>
  <div class="page-container">
    <div v-if="pending" class="flex justify-center items-center h-64">
      <el-skeleton :rows="6" animated />
    </div>
    <div v-else>
      <support-tabs model-value="faq" />
      <div class="page-header">
        <h1 class="page-title">{{ $t('navigation.faq') }}</h1>
        <app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
      </div>

      <div class="page-content">
        <question-filter
          v-model="filters"
          :product-type-options="productTypeOptions"
          :product-options="productOptions"
          :question-type-options="questionTypeOptions"
        />

        <question-list :questions="paginatedQuestions" />

        <el-pagination
          v-model:current-page="page"
          class="justify-center pagination-container"
          layout="prev, pager, next"
          hide-on-single-page
          :page-size="questionsPerPage"
          :total="filteredQuestions.length"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  const localePath = useLocalePath();
  const route = useRoute();

  const filters = reactive({
    selectedQuestionType: null as string | null,
    selectedProduct: null as string | null,
    selectedProductType: null as string | null,
    keyword: '',
  });

  const page = ref(1);
  const questionsPerPage = 10;

  const focusQuestionId = ref<string | null>(
    route.query.focus as string | null
  );

  const breadcrumbItems = [
    { label: $t('navigation.home'), to: localePath('/') },
    { label: $t('navigation.support'), to: localePath('/support') },
    { label: $t('navigation.faq') },
  ];

  const { data: questions, pending, error } = await useQuestionList();

  const questionTypeOptions = computed(() => {
    const types: QuestionTypeView[] = [];
    questions.value.forEach((q: QuestionListView) => {
      if (!types.some((t) => t.id === q.type.id)) {
        if (q.type.id === '-1') {
          types.push({
            id: '-1',
            name: $t('product-filter.misc'),
          });
        } else {
          types.push(q.type);
        }
      }
    });
    return types;
  });

  const productTypeOptions = computed(() => {
    const types: QuestionListProductType[] = [];
    questions.value.forEach((q: QuestionListView) => {
      q.products.forEach((product: QuestionListProduct) => {
        const productType = product.type;
        if (!types.some((p) => p.id === productType.id)) {
          types.push(productType);
        }
      });
    });
    return types;
  });

  const productOptions = computed(() => {
    if (!filters.selectedProductType) return [];
    const products: QuestionListProduct[] = [];
    questions.value.forEach((q: QuestionListView) => {
      q.products.forEach((product: QuestionListProduct) => {
        if (
          product.type.id === filters.selectedProductType &&
          !products.some((p) => p.id === product.id)
        ) {
          products.push(product);
        }
      });
    });
    return products;
  });

  const filteredQuestions = computed(() => {
    const fuzzyMatchedQuestions = fuzzyMatch(questions.value, {
      keyword: filters.keyword,
      keys: ['title'],
      threshold: 0.6,
    });
    return fuzzyMatchedQuestions.filter((question: QuestionListView) => {
      const matchProduct = filters.selectedProduct
        ? question.products?.some(
            (product: QuestionListProduct) =>
              product.id === filters.selectedProduct
          )
        : filters.selectedProductType
          ? question.products?.some(
              (product: QuestionListProduct) =>
                product.type.id === filters.selectedProductType
            )
          : true;

      const matchQuestionType = filters.selectedQuestionType
        ? question.type.id === filters.selectedQuestionType
        : true;

      return matchProduct && matchQuestionType;
    });
  });

  const paginatedQuestions = computed(() => {
    const start = (page.value - 1) * questionsPerPage;
    const end = page.value * questionsPerPage;
    return filteredQuestions.value.slice(start, end);
  });

  watch(
    focusQuestionId,
    async (focusId) => {
      if (!focusId) return;
      if (!import.meta.client) return;

      await nextTick();

      const question = filteredQuestions.value.find((q) => q.id === focusId);
      if (!question) return;

      const targetIndex = filteredQuestions.value.indexOf(question);
      const targetPage = Math.floor(targetIndex / questionsPerPage) + 1;
      onMounted(() => {
        if (page.value !== targetPage) {
          page.value = targetPage;
        }
      });
    },
    { immediate: true }
  );

  watch(
    () => filters.selectedProductType,
    () => {
      filters.selectedProduct = null;
    }
  );

  watch(error, (value) => {
    if (value) {
      logger.error('数据获取失败: ', value);
    }
  });

  const pageTitle = $t('page-title.faq');
  usePageSeo({
    title: pageTitle,
  });
</script>

<style scoped>
  .page-container {
    max-width: 1200px;
    margin: 0 auto;
  }

  .page-header {
    display: flex;
    padding: 2rem 2rem 0rem;
  }

  .page-title {
    font-size: 2rem;
    font-weight: bold;
    color: var(--el-color-primary);
    margin-bottom: 1rem;
  }

  .breadcrumb {
    margin-left: auto;
  }

  .page-content {
    padding: 1rem 2rem 2rem;
  }
  .pagination-container {
    margin-top: 2rem;
  }

  :deep(.el-pagination) {
    .btn-prev,
    .btn-next {
      .el-icon {
        font-size: 24px;
      }
    }

    .el-pager {
      gap: 0.5rem;
    }
    .el-pager li {
      font-size: 1rem;
      /* border: 1px solid #409eff; */
      border-radius: 50%;

      &:hover {
        background-color: #ecf5ff;
      }

      &.is-active {
        background-color: var(--el-color-primary);
        color: #fff;
      }
    }
  }
</style>
