<script setup lang="ts">
import { LinkOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { ArticleListItem, ArticleListParams } from '@geo/shared-types'
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import type { TableColumnsType } from 'ant-design-vue'
import { message } 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 } 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,
  hasActiveGenerationStatus,
} from '@/lib/display'
import { formatError } from '@/lib/errors'
import { useCompanyStore } from '@/stores/company'

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

const publishModalOpen = ref(false)
const selectedPublishArticleId = ref<number | null>(null)
const articleDrawerOpen = ref(false)
const selectedArticleId = ref<number | null>(null)
const page = ref(1)
const pageSize = ref(10)
const createdRange = ref<[Dayjs, Dayjs] | null>(null)

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

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

const articleParams = computed<ArticleListParams>(() => {
  const params: ArticleListParams = {
    page: page.value,
    page_size: pageSize.value,
    source_type: 'imitation',
  }

  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 articleListQuery = useQuery({
  queryKey: computed(() => ['articles', 'list', companyStore.currentBrandId, articleParams.value]),
  enabled: computed(() => Boolean(companyStore.currentBrandId)),
  queryFn: () => articlesApi.list(articleParams.value),
})

let articlePollingTimer: number | null = null

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

const { regeneratingArticleId, handleRegenerate } = useArticleRegenerateAction()

const generateStatusOptions = computed(() => [
  { 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 articleColumns = computed<TableColumnsType<ArticleListItem>>(() => [
  {
    title: t('common.title'),
    dataIndex: 'title',
    key: 'title',
    width: 460,
    className: 'imitation-view__title-column',
  },
  {
    title: t('imitation.list.sourceArticle'),
    dataIndex: 'source_url',
    key: 'source',
    width: 440,
    className: 'imitation-view__source-column',
  },
  {
    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 resolveImitationSourceTitle(article: ArticleListItem): string {
  return article.source_title?.trim() || ''
}

function resolveImitationSourceURL(article: ArticleListItem): string {
  return article.source_url?.trim() || ''
}

watch(
  () => articleListQuery.data.value?.items || [],
  (items: ArticleListItem[]) => {
    const hasGeneratingArticles = items.some((item) =>
      hasActiveGenerationStatus(item.generate_status),
    )

    if (hasGeneratingArticles) {
      startArticlePolling()
      return
    }

    stopArticlePolling()
  },
  { immediate: true },
)

onBeforeUnmount(() => {
  stopArticlePolling()
})

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

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

function openCreate(): void {
  if (!companyStore.currentBrandId) {
    message.warning(t('templates.wizard.messages.selectBrandBeforeQuestion'))
    return
  }
  void router.push({ name: 'article-imitation-create' })
}

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 openPreview(article: ArticleListItem): void {
  selectedArticleId.value = article.id
  articleDrawerOpen.value = true
}

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

function startArticlePolling(): void {
  if (articlePollingTimer !== null) {
    return
  }

  articlePollingTimer = window.setInterval(() => {
    void queryClient.invalidateQueries({ queryKey: ['articles'] })
    void articleListQuery.refetch()
  }, 3000)
}

function stopArticlePolling(): void {
  if (articlePollingTimer === null) {
    return
  }

  window.clearInterval(articlePollingTimer)
  articlePollingTimer = null
}

async function handleDelete(articleId: number): Promise<void> {
  await deleteMutation.mutateAsync(articleId)
}

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'))
  }
}
</script>

<template>
  <div class="imitation-view">
    <section class="imitation-view__top-card">
      <div class="imitation-view__header">
        <div class="imitation-view__header-title">
          <h2>{{ t('route.imitation.title') }}</h2>
          <p>{{ t('route.imitation.description') }}</p>
        </div>
        <div class="imitation-view__header-actions">
          <a-button type="primary" :disabled="!companyStore.currentBrandId" @click="openCreate">
            <template #icon><PlusOutlined /></template>
            {{ t('imitation.actions.create') }}
          </a-button>
        </div>
      </div>

      <a-divider style="margin: 0; border-color: #f0f0f0" />

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

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

          <div class="imitation-view__filter-item">
            <label>{{ t('imitation.filters.createdTime') }}:</label>
            <a-range-picker
              v-model:value="createdRange"
              allow-clear
              show-time
              format="YYYY-MM-DD HH:mm"
              :placeholder="[
                t('imitation.filters.createdTimeStart'),
                t('imitation.filters.createdTimeEnd'),
              ]"
              @change="applyFilters"
            />
          </div>

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

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

    <section class="imitation-view__table-card">
      <div class="imitation-view__table-head">
        <div>
          <p class="eyebrow">{{ t('imitation.list.eyebrow') }}</p>
          <h3>
            {{ t('imitation.list.count', { count: articleListQuery.data.value?.total ?? 0 }) }}
          </h3>
        </div>
        <a-button type="link" @click="articleListQuery.refetch()">
          {{ t('common.refresh') }}
        </a-button>
      </div>

      <a-table
        :columns="articleColumns"
        :data-source="articleListQuery.data.value?.items || []"
        :loading="articleListQuery.isPending.value"
        row-key="id"
        :scroll="{ x: 1420 }"
        :pagination="{
          current: page,
          pageSize,
          total: articleListQuery.data.value?.total || 0,
          showSizeChanger: true,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }"
      >
        <template #emptyText>{{ t('imitation.list.empty') }}</template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="imitation-view__title-cell">
              <strong>{{ record.title || t('article.untitled') }}</strong>
              <ArticleSourceMeta
                :source-type="record.source_type"
                :generation-mode="record.generation_mode"
                :created-at="record.created_at"
              />
            </div>
          </template>

          <template v-else-if="column.key === 'source'">
            <div
              v-if="resolveImitationSourceTitle(record) || resolveImitationSourceURL(record)"
              class="imitation-view__source-cell"
            >
              <a
                v-if="resolveImitationSourceURL(record)"
                class="imitation-view__source-link"
                :href="resolveImitationSourceURL(record)"
                target="_blank"
                rel="noopener noreferrer"
                :title="resolveImitationSourceURL(record)"
                @click.stop
              >
                <LinkOutlined />
                <span class="imitation-view__source-copy">
                  <span
                    v-if="resolveImitationSourceTitle(record)"
                    class="imitation-view__source-title"
                  >
                    {{ resolveImitationSourceTitle(record) }}
                  </span>
                  <span class="imitation-view__source-url">
                    {{ resolveImitationSourceURL(record) }}
                  </span>
                </span>
              </a>
              <span v-else class="imitation-view__source-copy">
                <span class="imitation-view__source-title">
                  {{ resolveImitationSourceTitle(record) }}
                </span>
              </span>
            </div>
            <span v-else>--</span>
          </template>

          <template v-else-if="column.key === 'generate_status'">
            <div class="imitation-view__status-cell">
              <ArticleGenerateStatus :status="record.generate_status" />
              <a-tooltip
                v-if="record.generate_status === 'failed' && record.generation_error_message"
              >
                <template #title>{{ record.generation_error_message }}</template>
                <span class="imitation-view__error-text">
                  {{ record.generation_error_message }}
                </span>
              </a-tooltip>
            </div>
          </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('imitation.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="openPreview(record)"
              @copy="copyArticle(record.id)"
              @regenerate="handleRegenerate(record)"
              @delete="handleDelete(record.id)"
            />
          </template>
        </template>
      </a-table>
    </section>

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

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

<style scoped>
.imitation-view {
  display: flex;
  flex-direction: column;
  gap: 22px;
}

.imitation-view__top-card {
  overflow: hidden;
  border: 1px solid #e6edf5;
  border-radius: 12px;
  background: #fff;
}

.imitation-view__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 24px;
}

.imitation-view__header-title h2 {
  margin: 0;
  color: #1a1a1a;
  font-size: 20px;
  font-weight: 600;
  line-height: 1.4;
}

.imitation-view__header-title p {
  margin: 6px 0 0;
  color: #8c8c8c;
  font-size: 13px;
}

.imitation-view__filters {
  padding: 20px 24px;
}

.imitation-view__filters-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px 24px;
}

.imitation-view__filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.imitation-view__filter-item label {
  color: #101828;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
}

.imitation-view__filter-item :deep(.ant-select) {
  min-width: 140px;
}

.imitation-view__filter-item :deep(.ant-picker) {
  width: 320px;
}

.imitation-view__filter-item :deep(.ant-input-affix-wrapper),
.imitation-view__filter-item :deep(.ant-input-search) {
  width: 240px;
}

.imitation-view__reset-btn {
  flex-shrink: 0;
  margin-left: auto;
}

.imitation-view__table-card {
  padding: 24px;
  border: 1px solid #e6edf5;
  border-radius: 12px;
  background: #fff;
}

.imitation-view__table-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 18px;
}

.imitation-view__table-head h3 {
  margin: 6px 0 0;
  font-size: 24px;
}

.imitation-view__title-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.imitation-view__title-cell > strong {
  color: #101828;
  font-size: 14px;
  font-weight: 600;
  line-height: 20px;
}

:deep(.imitation-view__title-column),
:deep(.imitation-view__source-column) {
  vertical-align: top;
}

.imitation-view__source-cell {
  min-width: 0;
}

.imitation-view__source-link {
  display: inline-flex;
  max-width: 100%;
  align-items: center;
  gap: 8px;
  color: #5b6f8f;
  font-size: 13px;
  line-height: 20px;
}

.imitation-view__source-link :deep(.anticon) {
  flex: 0 0 auto;
}

.imitation-view__source-link:hover {
  color: #1677ff;
}

.imitation-view__source-copy {
  display: flex;
  min-width: 0;
  flex-direction: column;
  gap: 4px;
}

.imitation-view__source-title,
.imitation-view__source-url {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.imitation-view__source-title {
  color: #101828;
  font-size: 13px;
  font-weight: 500;
  line-height: 20px;
}

.imitation-view__source-url {
  color: #1677ff;
  font-size: 12px;
  line-height: 18px;
}

.imitation-view__status-cell {
  display: flex;
  min-width: 0;
  flex-direction: column;
  align-items: flex-start;
  gap: 6px;
}

.imitation-view__error-text {
  display: block;
  max-width: 118px;
  overflow: hidden;
  color: #cf1322;
  font-size: 12px;
  line-height: 18px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@media (max-width: 1200px) {
  .imitation-view__filter-item :deep(.ant-picker) {
    width: 280px;
  }
}

@media (max-width: 720px) {
  .imitation-view__table-head {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
