<script setup lang="ts">
import { 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, reactive, ref } 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 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 { getPublishStatusMeta } from '@/lib/display'
import { formatError } from '@/lib/errors'

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

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
  keyword?: string
  created_from?: string
  created_to?: string
}>({
  keyword: '',
})

const appliedFilters = reactive<{
  publish_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: 'free_create',
  }

  if (appliedFilters.publish_status) {
    params.publish_status = appliedFilters.publish_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', articleParams.value]),
  queryFn: () => articlesApi.list(articleParams.value),
})

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

const createMutation = useMutation({
  mutationFn: () => articlesApi.create({}),
  onSuccess: (data) => {
    void queryClient.invalidateQueries({ queryKey: ['workspace'] })
    void router.push({ name: 'article-editor', params: { id: String(data.id) } })
  },
  onError: (error) => {
    message.error(formatError(error) || t('freeCreate.createError'))
  },
})

const { regeneratingArticleId, handleRegenerate } = useArticleRegenerateAction()

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',
  },
  {
    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,
    align: 'right',
  },
])

function applyFilters(): void {
  page.value = 1
  appliedFilters.publish_status = draftFilters.publish_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.keyword = ''
  createdRange.value = null
  applyFilters()
}

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
}

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

function handleCreate(): void {
  createMutation.mutate()
}

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="free-create-view">
    <section class="free-create-view__top-card">
      <div class="free-create-view__header">
        <div class="free-create-view__header-title">
          <h2>{{ t('route.freeCreate.title') }}</h2>
          <p>{{ t('route.freeCreate.description') }}</p>
        </div>
        <div class="free-create-view__header-actions">
          <a-button type="primary" :loading="createMutation.isPending.value" @click="handleCreate">
            <template #icon><PlusOutlined /></template>
            {{ t('freeCreate.actions.create') }}
          </a-button>
        </div>
      </div>

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

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

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

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

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

    <section class="free-create-view__table-card">
      <div class="free-create-view__table-head">
        <div>
          <p class="eyebrow">{{ t('freeCreate.list.eyebrow') }}</p>
          <h3>
            {{ t('freeCreate.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"
        :pagination="{
          current: page,
          pageSize,
          total: articleListQuery.data.value?.total || 0,
          showSizeChanger: true,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }"
      >
        <template #emptyText>{{ t('freeCreate.list.empty') }}</template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="free-create-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 === '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('freeCreate.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>
.free-create-view {
  display: flex;
  flex-direction: column;
  gap: 22px;
}

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

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

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

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

.free-create-view__header-actions {
  display: flex;
  gap: 12px;
}

.free-create-view__filters {
  padding: 20px 24px;
}

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

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

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

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

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

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

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

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

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

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

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

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

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