<script setup lang="ts">
import type { ArticleListItem, ArticleListParams } from '@geo/shared-types'
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { message, type TableColumnsType } from 'ant-design-vue'
import type { Dayjs } from 'dayjs'
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

import ArticleActionGroup from '@/components/ArticleActionGroup.vue'
import ArticleDetailDrawer from '@/components/ArticleDetailDrawer.vue'
import ArticleGenerateStatus from '@/components/ArticleGenerateStatus.vue'
import ArticlePublishStatus from '@/components/ArticlePublishStatus.vue'
import ArticleSourceMeta from '@/components/ArticleSourceMeta.vue'
import PublishArticleModal from '@/components/PublishArticleModal.vue'
import { articlesApi, promptRulesApi } from '@/lib/api'
import { buildArticleClipboardContent, resolveArticleActionState } from '@/lib/article-list-actions'
import { useArticleRegenerateAction } from '@/lib/article-regenerate-action'
import { copyTextToClipboard } from '@/lib/clipboard'
import { getGenerateStatusMeta, getPublishStatusMeta } from '@/lib/display'
import { formatError } from '@/lib/errors'
import { formatPublishPlatformList } from '@/lib/publish-platforms'
import { useCompanyStore } from '@/stores/company'

const queryClient = useQueryClient()
const router = useRouter()
const { t } = useI18n()
const companyStore = useCompanyStore()

const page = ref(1)
const pageSize = ref(20)
const draftGenerationRange = ref<[Dayjs, Dayjs] | null>(null)

const draftFilters = reactive<{
  prompt_rule_id?: number
  publish_status?: string
  generate_status?: string
  keyword?: string
}>({
  keyword: '',
})

const appliedFilters = reactive<{
  prompt_rule_id?: number
  publish_status?: string
  generate_status?: string
  keyword?: string
  created_from?: string
  created_to?: string
}>({
  keyword: '',
})

const articleDrawerOpen = ref(false)
const selectedArticleId = ref<number | null>(null)
const publishModalOpen = ref(false)
const selectedPublishArticleId = ref<number | null>(null)

const rulesQuery = useQuery({
  queryKey: computed(() => ['promptRules', 'simple', companyStore.currentBrandId]),
  enabled: computed(() => Boolean(companyStore.currentBrandId)),
  queryFn: () => promptRulesApi.listSimple(),
})

const ruleOptions = computed(() =>
  (rulesQuery.data.value ?? []).map((r) => ({ label: r.name, value: r.id })),
)

const generateStatusOptions = computed(() => [
  { label: getGenerateStatusMeta('draft').label, value: 'draft' },
  { label: getGenerateStatusMeta('generating').label, value: 'generating' },
  { label: getGenerateStatusMeta('completed').label, value: 'completed' },
  { label: getGenerateStatusMeta('failed').label, value: 'failed' },
])

const publishStatusOptions = computed(() => [
  { label: getPublishStatusMeta('unpublished').label, value: 'unpublished' },
  { label: getPublishStatusMeta('publishing').label, value: 'publishing' },
  { label: getPublishStatusMeta('success').label, value: 'success' },
  { label: getPublishStatusMeta('partial_success').label, value: 'partial_success' },
  { label: getPublishStatusMeta('failed').label, value: 'failed' },
])

const articleParams = computed<ArticleListParams>(() => {
  const params: ArticleListParams = {
    page: page.value,
    page_size: pageSize.value,
    source_type: 'custom_generation',
  }
  if (appliedFilters.prompt_rule_id) params.prompt_rule_id = appliedFilters.prompt_rule_id
  if (appliedFilters.publish_status) params.publish_status = appliedFilters.publish_status
  if (appliedFilters.generate_status) params.generate_status = appliedFilters.generate_status
  if (appliedFilters.keyword?.trim()) params.keyword = appliedFilters.keyword.trim()
  if (appliedFilters.created_from) params.created_from = appliedFilters.created_from
  if (appliedFilters.created_to) params.created_to = appliedFilters.created_to
  return params
})

const listQuery = useQuery({
  queryKey: computed(() => [
    'articles',
    'list',
    companyStore.currentBrandId,
    'custom_generation',
    articleParams.value,
  ]),
  enabled: computed(() => Boolean(companyStore.currentBrandId)),
  queryFn: () => articlesApi.list(articleParams.value),
})

let pollingTimer: number | null = null

const deleteMutation = useMutation({
  mutationFn: (id: number) => articlesApi.remove(id),
  onSuccess: async () => {
    message.success(t('templates.list.deleteSuccess'))
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['articles'] }),
      queryClient.invalidateQueries({ queryKey: ['workspace'] }),
    ])
  },
  onError: (error) => message.error(formatError(error)),
})

const { regeneratingArticleId, handleRegenerate } = useArticleRegenerateAction()

const columns = computed<TableColumnsType<ArticleListItem>>(() => [
  { title: t('custom.article.titleColumn'), dataIndex: 'title', key: 'title', width: 340 },
  {
    title: t('custom.filters.promptRule'),
    dataIndex: 'prompt_rule_name',
    key: 'prompt_rule_name',
    width: 160,
  },
  {
    title: t('custom.schedule.autoPublishPlatforms'),
    dataIndex: 'auto_publish_platforms',
    key: 'auto_publish_platforms',
    width: 180,
  },
  {
    title: t('common.generateStatus'),
    dataIndex: 'generate_status',
    key: 'generate_status',
    width: 128,
  },
  {
    title: t('common.publishStatus'),
    dataIndex: 'publish_status',
    key: 'publish_status',
    width: 128,
  },
  { title: t('common.wordCount'), dataIndex: 'word_count', key: 'word_count', width: 100 },
  { title: t('common.actions'), key: 'actions', width: 156, fixed: 'right', align: 'right' },
])

function applyFilters(): void {
  page.value = 1
  appliedFilters.prompt_rule_id = draftFilters.prompt_rule_id
  appliedFilters.publish_status = draftFilters.publish_status
  appliedFilters.generate_status = draftFilters.generate_status
  appliedFilters.keyword = draftFilters.keyword?.trim() || ''
  appliedFilters.created_from = draftGenerationRange.value?.[0]?.toISOString()
  appliedFilters.created_to = draftGenerationRange.value?.[1]?.toISOString()
}

function resetFilters(): void {
  draftFilters.prompt_rule_id = undefined
  draftFilters.publish_status = undefined
  draftFilters.generate_status = undefined
  draftFilters.keyword = ''
  draftGenerationRange.value = null
  applyFilters()
}

function openDetail(article: ArticleListItem): void {
  selectedArticleId.value = article.id
  articleDrawerOpen.value = true
}

function openEditor(article: ArticleListItem): void {
  void router.push({ name: 'article-editor', params: { id: String(article.id) } })
}

function openPublish(article: ArticleListItem): void {
  selectedPublishArticleId.value = article.id
  publishModalOpen.value = true
}

function getDisplayTitle(article: ArticleListItem): string {
  if (
    (article.generate_status === 'generating' || article.generate_status === 'running') &&
    !article.title
  ) {
    return t('custom.article.titleGenerating')
  }
  return article.title || t('article.untitled')
}

function handleTableChange(nextPage: number, nextPageSize: number): void {
  page.value = nextPage
  pageSize.value = nextPageSize
}

function startPolling(): void {
  if (pollingTimer !== null) return
  pollingTimer = window.setInterval(() => {
    void listQuery.refetch()
  }, 3000)
}

function stopPolling(): void {
  if (pollingTimer === null) return
  window.clearInterval(pollingTimer)
  pollingTimer = null
}

async function copyArticle(articleId: number): Promise<void> {
  try {
    const detail = await articlesApi.detail(articleId)
    const content = buildArticleClipboardContent(detail)

    if (!content) {
      message.warning(t('common.noData'))
      return
    }

    await copyTextToClipboard(content)
    message.success(t('common.copySuccess'))
  } catch (error) {
    message.error(formatError(error) || t('common.noData'))
  }
}

watch(
  () => listQuery.data.value?.items ?? [],
  (items) => {
    const hasActive = items.some(
      (item) => item.generate_status === 'generating' || item.generate_status === 'running',
    )
    if (hasActive) {
      startPolling()
    } else {
      stopPolling()
    }
  },
  { immediate: true },
)

watch(
  () => companyStore.currentBrandId,
  () => {
    draftFilters.prompt_rule_id = undefined
    appliedFilters.prompt_rule_id = undefined
    page.value = 1
  },
)

onBeforeUnmount(() => {
  stopPolling()
})
</script>

<template>
  <div class="custom-article-tab">
    <div class="custom-article-tab__filters">
      <div class="custom-article-tab__filter-item">
        <label>{{ t('custom.filters.promptRule') }}:</label>
        <a-select
          v-model:value="draftFilters.prompt_rule_id"
          allow-clear
          :options="ruleOptions"
          :placeholder="t('common.selectPlease')"
          :loading="rulesQuery.isPending.value"
          @change="applyFilters"
        />
      </div>

      <div class="custom-article-tab__filter-item">
        <label>{{ t('custom.filters.publishStatus') }}:</label>
        <a-select
          v-model:value="draftFilters.publish_status"
          allow-clear
          :options="publishStatusOptions"
          :placeholder="t('common.selectPlease')"
          @change="applyFilters"
        />
      </div>

      <div class="custom-article-tab__filter-item">
        <label>{{ t('custom.filters.generateStatus') }}:</label>
        <a-select
          v-model:value="draftFilters.generate_status"
          allow-clear
          :options="generateStatusOptions"
          :placeholder="t('common.selectPlease')"
          @change="applyFilters"
        />
      </div>

      <div class="custom-article-tab__filter-item">
        <label>{{ t('custom.filters.generateTime') }}:</label>
        <a-range-picker
          v-model:value="draftGenerationRange"
          allow-clear
          show-time
          format="YYYY-MM-DD HH:mm"
          @change="applyFilters"
        />
      </div>

      <div class="custom-article-tab__filter-item">
        <label>{{ t('custom.filters.title') }}:</label>
        <a-input-search
          v-model:value="draftFilters.keyword"
          :placeholder="t('templates.filters.keywordPlaceholder')"
          @search="applyFilters"
          @pressEnter="applyFilters"
        />
      </div>

      <a-button @click="resetFilters">{{ t('common.reset') }}</a-button>
    </div>

    <div class="custom-article-tab__head">
      <span class="custom-article-tab__count">
        {{ t('templates.list.count', { count: listQuery.data.value?.total ?? 0 }) }}
      </span>
      <a-button type="link" @click="listQuery.refetch()">
        {{ t('common.refresh') }}
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="listQuery.data.value?.items ?? []"
      :loading="listQuery.isPending.value"
      :pagination="{
        current: page,
        pageSize,
        total: listQuery.data.value?.total ?? 0,
        showSizeChanger: true,
      }"
      row-key="id"
      size="small"
      :scroll="{ x: 1000 }"
      @change="(p: any) => handleTableChange(p.current, p.pageSize)"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'title'">
          <div class="custom-article-tab__title-cell">
            <a class="custom-article-tab__title-link" @click="openDetail(record)">
              {{ getDisplayTitle(record) }}
            </a>
            <ArticleSourceMeta
              :source-type="record.source_type"
              :generation-mode="record.generation_mode"
              :created-at="record.created_at"
            />
          </div>
        </template>
        <template v-else-if="column.key === 'prompt_rule_name'">
          {{ record.prompt_rule_name || '--' }}
        </template>
        <template v-else-if="column.key === 'auto_publish_platforms'">
          {{ formatPublishPlatformList(record.auto_publish_platforms) }}
        </template>
        <template v-else-if="column.key === 'generate_status'">
          <ArticleGenerateStatus :status="record.generate_status" />
        </template>
        <template v-else-if="column.key === 'publish_status'">
          <ArticlePublishStatus :status="record.publish_status" :article-id="record.id" />
        </template>
        <template v-else-if="column.key === 'word_count'">
          {{ record.word_count || '--' }}
        </template>
        <template v-else-if="column.key === 'actions'">
          <ArticleActionGroup
            v-bind="resolveArticleActionState(record)"
            :delete-confirm-title="t('templates.list.deleteConfirm')"
            :delete-loading="deleteMutation.isPending.value"
            :regenerate-confirm-title="t('common.regenerateConfirm')"
            :regenerate-loading="regeneratingArticleId === record.id"
            @publish="openPublish(record)"
            @edit="openEditor(record)"
            @preview="openDetail(record)"
            @copy="copyArticle(record.id)"
            @regenerate="handleRegenerate(record)"
            @delete="deleteMutation.mutate(record.id)"
          />
        </template>
      </template>
    </a-table>

    <ArticleDetailDrawer
      :open="articleDrawerOpen"
      :article-id="selectedArticleId"
      @close="articleDrawerOpen = false"
    />

    <PublishArticleModal v-model:open="publishModalOpen" :article-id="selectedPublishArticleId" />
  </div>
</template>

<style scoped>
.custom-article-tab__filters {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 12px;
  margin-bottom: 16px;
}

.custom-article-tab__filter-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 160px;
}

.custom-article-tab__filter-item label {
  font-size: 12px;
  color: #8c8c8c;
}

.custom-article-tab__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.custom-article-tab__count {
  font-size: 13px;
  color: #8c8c8c;
}

.custom-article-tab__title-link {
  display: inline-block;
  color: #434343;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  line-height: 1.6;
}

.custom-article-tab__title-link:hover {
  color: #1677ff;
}

.custom-article-tab__title-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 4px 0;
}
</style>
