<script setup lang="ts">
import { CopyOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import type { MediaSupplyOrderDetail } from '@geo/shared-types'
import { useQuery } from '@tanstack/vue-query'
import { message, type TableColumnsType } from 'ant-design-vue'
import { computed, onBeforeUnmount, ref, watch } from 'vue'

import { mediaSupplyApi } from '@/lib/api'
import { formatDateTime } from '@/lib/display'
import { formatStoredErrorMessage } from '@/lib/errors'

const page = ref(1)
const pageSize = ref(10)
const status = ref('')

function copyToClipboard(text?: string | null): void {
  const url = String(text ?? '').trim()
  if (!url) {
    message.warning('链接为空，无法复制')
    return
  }
  void navigator.clipboard
    .writeText(url)
    .then(() => {
      message.success('已复制到剪贴板')
    })
    .catch(() => {
      message.error('复制失败，请手动复制')
    })
}

const ordersQuery = useQuery({
  queryKey: computed(() => ['media-supply', 'orders', page.value, pageSize.value, status.value]),
  queryFn: () =>
    mediaSupplyApi.listOrders({
      page: page.value,
      page_size: pageSize.value,
      status: status.value || undefined,
    }),
})

const orders = computed(() => ordersQuery.data.value?.items ?? [])
const total = computed(() => ordersQuery.data.value?.total ?? 0)

const columns = computed<TableColumnsType<MediaSupplyOrderDetail>>(() => [
  { title: '标题', key: 'title', dataIndex: 'title', width: 300, fixed: 'left' },
  { title: '状态', key: 'status', dataIndex: 'status', width: 120 },
  {
    title: '金额',
    key: 'sell_total_cents',
    dataIndex: 'sell_total_cents',
    width: 130,
    align: 'right',
  },
  { title: '扣款', key: 'wallet', width: 150 },
  { title: '媒体', key: 'items', width: 110, align: 'right' },
  { title: '回链', key: 'backlinks', width: 220 },
  { title: '外部单号', key: 'external_order_code', dataIndex: 'external_order_code', width: 170 },
  { title: '创建时间', key: 'created_at', dataIndex: 'created_at', width: 170 },
  { title: '错误', key: 'error_message', dataIndex: 'error_message', width: 260 },
])

function refresh(): void {
  void ordersQuery.refetch()
}

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

function applyStatus(nextStatus: string): void {
  status.value = nextStatus
  page.value = 1
}

function handleStatusChange(value: string | number): void {
  applyStatus(String(value))
}

function orderStatusMeta(order: MediaSupplyOrderDetail): { label: string; color: string } {
  switch (order.status) {
    case 'queued':
      return { label: '排队中', color: 'processing' }
    case 'submitting':
      return { label: '投稿中', color: 'processing' }
    case 'submitted':
      return hasPublishedBacklink(order)
        ? { label: '已发表', color: 'success' }
        : { label: '发表中', color: 'processing' }
    case 'failed':
      return order.wallet_refunded_at && order.supplier_status === 'rejected'
        ? { label: '已退稿', color: 'default' }
        : { label: '投稿失败', color: 'error' }
    default:
      return { label: order.status || '--', color: 'default' }
  }
}

function walletMeta(order: MediaSupplyOrderDetail): { label: string; color: string } {
  if (order.wallet_refunded_at) {
    return { label: '已退款', color: 'default' }
  }
  if (order.wallet_debited_at) {
    return { label: '已扣款', color: 'success' }
  }
  return { label: '未扣款', color: 'warning' }
}

function backlinkItems(order: MediaSupplyOrderDetail) {
  return (order.items ?? []).filter((item) => Boolean(item.external_article_url))
}

function hasPublishedBacklink(order: MediaSupplyOrderDetail): boolean {
  return backlinkItems(order).length > 0
}

function pendingBacklinkCount(order: MediaSupplyOrderDetail): number {
  return (order.items ?? []).filter((item) => !item.external_article_url).length
}

const shouldPollOrders = computed(() =>
  orders.value.some(
    (order) =>
      order.status === 'queued' ||
      order.status === 'submitting' ||
      (order.status === 'submitted' && pendingBacklinkCount(order) > 0),
  ),
)

let pollingTimer: ReturnType<typeof setInterval> | undefined

function stopOrderPolling(): void {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = undefined
  }
}

function startOrderPolling(): void {
  if (pollingTimer) {
    return
  }
  pollingTimer = setInterval(() => {
    if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
      return
    }
    if (!ordersQuery.isFetching.value) {
      void ordersQuery.refetch()
    }
  }, 10_000)
}

watch(
  shouldPollOrders,
  (enabled) => {
    if (enabled) {
      startOrderPolling()
    } else {
      stopOrderPolling()
    }
  },
  { immediate: true },
)

onBeforeUnmount(stopOrderPolling)

function mediaNames(order: MediaSupplyOrderDetail): string[] {
  const seen = new Set<string>()
  const names: string[] = []
  for (const item of order.items ?? []) {
    const name = String(item.resource_name_snapshot ?? '').trim()
    if (!name || seen.has(name)) {
      continue
    }
    seen.add(name)
    names.push(name)
  }
  return names
}

function mediaSummary(order: MediaSupplyOrderDetail): string {
  const names = mediaNames(order)
  if (names.length === 0) {
    return '--'
  }
  return names.join('、')
}

function backlinkSummary(order: MediaSupplyOrderDetail): string {
  const ready = backlinkItems(order).length
  const totalItems = order.items?.length ?? 0
  if (!totalItems) {
    return '--'
  }
  if (ready <= 0) {
    return '待回传'
  }
  return `${ready}/${totalItems} 已回传`
}

function safeURL(value?: string | null): string {
  const raw = String(value ?? '').trim()
  if (/^https?:\/\//i.test(raw)) {
    return raw
  }
  return ''
}

function backlinkURLText(value?: string | null): string {
  return safeURL(value) || '--'
}

function formatMoney(cents?: number | null): string {
  if (typeof cents !== 'number' || !Number.isFinite(cents)) {
    return '--'
  }
  return `￥${(cents / 100).toFixed(2)}`
}

function formatSellPrice(cents?: number | null): string {
  if (typeof cents !== 'number' || !Number.isFinite(cents)) {
    return '--'
  }
  return `￥${Math.ceil(cents / 100)}`
}

function formatOrderError(message?: string | null): string {
  return formatStoredErrorMessage(message) || '--'
}
</script>

<template>
  <div class="media-supply-orders">
    <section class="orders-toolbar">
      <a-segmented
        :value="status"
        :options="[
          { label: '全部', value: '' },
          { label: '排队中', value: 'queued' },
          { label: '投稿中', value: 'submitting' },
          { label: '发表中/已发表', value: 'submitted' },
          { label: '退稿/失败', value: 'failed' },
        ]"
        @change="handleStatusChange"
      />
      <div class="orders-toolbar-actions">
        <button type="button" class="toolbar-btn-refresh" @click="refresh">
          <ReloadOutlined :class="{ 'refresh-spinning': ordersQuery.isFetching.value }" />
          刷新
        </button>
      </div>
    </section>

    <section class="orders-table-wrap">
      <a-table
        :columns="columns"
        :data-source="orders"
        :loading="ordersQuery.isPending.value"
        :pagination="{
          current: page,
          pageSize,
          total,
          showSizeChanger: true,
          showTotal: (value: number) => `共 ${value} 条`,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }"
        row-key="id"
        :scroll="{ x: 1580 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <div class="title-cell">
              <a-tooltip :title="record.title">
                <strong>{{ record.title }}</strong>
              </a-tooltip>
              <a-tooltip :title="record.order_brand || record.remark || '--'">
                <span>{{ record.order_brand || record.remark || '--' }}</span>
              </a-tooltip>
            </div>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="orderStatusMeta(record).color">
              {{ orderStatusMeta(record).label }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'sell_total_cents'">
            <strong>{{ formatSellPrice(record.sell_total_cents) }}</strong>
          </template>
          <template v-else-if="column.key === 'wallet'">
            <a-tag :color="walletMeta(record).color">{{ walletMeta(record).label }}</a-tag>
            <span class="muted">{{ formatMoney(record.wallet_debit_cents) }}</span>
          </template>
          <template v-else-if="column.key === 'items'">
            <a-tooltip :title="mediaSummary(record)">
              <span class="media-cell">{{ mediaSummary(record) }}</span>
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'backlinks'">
            <div v-if="backlinkItems(record).length" class="backlinks-cell">
              <div v-for="item in backlinkItems(record)" :key="item.id" class="backlink-item-row">
                <a-tooltip :title="item.external_article_url">
                  <a
                    :href="safeURL(item.external_article_url)"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="backlink-anchor"
                  >
                    {{ backlinkURLText(item.external_article_url) }}
                  </a>
                </a-tooltip>
                <a-tooltip title="复制链接">
                  <button
                    type="button"
                    class="copy-link-btn"
                    @click.stop="copyToClipboard(item.external_article_url)"
                  >
                    <CopyOutlined />
                  </button>
                </a-tooltip>
              </div>
              <span v-if="pendingBacklinkCount(record)" class="muted">
                {{ pendingBacklinkCount(record) }} 个待回传
              </span>
            </div>
            <span v-else>{{ backlinkSummary(record) }}</span>
          </template>
          <template v-else-if="column.key === 'external_order_code'">
            {{ record.external_order_code || '--' }}
          </template>
          <template v-else-if="column.key === 'created_at'">
            {{ formatDateTime(record.created_at) }}
          </template>
          <template v-else-if="column.key === 'error_message'">
            <a-tooltip v-if="record.error_message" :title="formatOrderError(record.error_message)">
              <span class="error-text">{{ formatOrderError(record.error_message) }}</span>
            </a-tooltip>
            <span v-else>--</span>
          </template>
        </template>
      </a-table>
    </section>
  </div>
</template>

<style scoped>
.media-supply-orders {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.orders-toolbar,
.orders-table-wrap {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
}

.orders-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 14px 20px;
}

/* Custom segmented control styling */
.orders-toolbar :deep(.ant-segmented) {
  background: #f1f5f9;
  border-radius: 8px;
  padding: 3px;
}

.orders-toolbar :deep(.ant-segmented-item-selected) {
  background: #fff !important;
  color: #ff1831 !important;
  font-weight: 700;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.orders-toolbar :deep(.ant-segmented-item:hover) {
  color: #ff1831 !important;
}

.orders-toolbar-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-btn-refresh {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 36px;
  padding: 0 14px;
  font-size: 13px;
  font-weight: 500;
  color: #475467;
  background: #fff;
  border: 1px solid #d0d5dd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.toolbar-btn-refresh:hover {
  background: #f9fafb;
  color: #1d2939;
  border-color: #98a2b3;
}

.toolbar-btn-sync {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 36px;
  padding: 0 16px;
  font-size: 13px;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(135deg, #ff1831, #ff5c6e);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(255, 24, 49, 0.05);
}

.toolbar-btn-sync:hover:not(:disabled) {
  background: linear-gradient(135deg, #e5152b, #e55256);
  transform: translateY(-0.5px);
  box-shadow: 0 4px 8px rgba(255, 24, 49, 0.15);
}

.toolbar-btn-sync:active:not(:disabled) {
  transform: translateY(0);
}

.toolbar-btn-sync:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.refresh-spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.orders-table-wrap {
  overflow: hidden;
  padding-top: 8px;
}

/* Custom table styling */
.orders-table-wrap :deep(.ant-table) {
  color: #344054;
  font-size: 13px;
}

.orders-table-wrap :deep(.ant-table-thead > tr > th) {
  background: #f8fafc !important;
  color: #475467 !important;
  font-weight: 600 !important;
  border-bottom: 1px solid #e2e8f0 !important;
  text-align: center;
}

.orders-table-wrap :deep(.ant-table-tbody > tr > td) {
  border-bottom: 1px solid #f1f5f9 !important;
  padding: 12px 16px !important;
}

/* Status and Wallet tag customized overrides */
.orders-table-wrap :deep(.ant-tag) {
  border-radius: 6px !important;
  font-size: 12px !important;
  font-weight: 600 !important;
  padding: 2px 8px !important;
  border: 1px solid transparent !important;
  text-align: center;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.orders-table-wrap :deep(.ant-tag-processing) {
  background: #eef2ff !important;
  border-color: #e0e7ff !important;
  color: #4f46e5 !important;
}

.orders-table-wrap :deep(.ant-tag-success) {
  background: #ecfdf5 !important;
  border-color: #d1fae5 !important;
  color: #059669 !important;
}

.orders-table-wrap :deep(.ant-tag-error) {
  background: #fff1f2 !important;
  border-color: #ffe4e6 !important;
  color: #e11d48 !important;
}

.orders-table-wrap :deep(.ant-tag-default) {
  background: #f8fafc !important;
  border-color: #e2e8f0 !important;
  color: #64748b !important;
}

.orders-table-wrap :deep(.ant-tag-warning) {
  background: #fffbeb !important;
  border-color: #fde68a !important;
  color: #d97706 !important;
}

/* Custom pagination overrides in crimson */
.orders-table-wrap :deep(.ant-pagination-item-active) {
  border-color: #ff1831 !important;
  background: #fff !important;
}

.orders-table-wrap :deep(.ant-pagination-item-active a) {
  color: #ff1831 !important;
}

.orders-table-wrap :deep(.ant-pagination-item:hover a) {
  color: #ff1831 !important;
}

.orders-table-wrap :deep(.ant-pagination-item:hover) {
  border-color: #ff1831 !important;
}

.orders-table-wrap :deep(.ant-pagination-prev:hover .ant-pagination-item-link),
.orders-table-wrap :deep(.ant-pagination-next:hover .ant-pagination-item-link) {
  border-color: #ff1831 !important;
  color: #ff1831 !important;
}

.orders-table-wrap :deep(.ant-select:hover .ant-select-selector),
.orders-table-wrap :deep(.ant-select-focused .ant-select-selector) {
  border-color: #ff1831 !important;
}

.orders-table-wrap :deep(.ant-select-dropdown .ant-select-item-option-selected) {
  background-color: #fff4f4 !important;
  color: #ff1831 !important;
}

.title-cell {
  display: flex;
  min-width: 0;
  flex-direction: column;
  gap: 4px;
}

.title-cell strong {
  color: #0f172a;
  font-size: 14px;
  font-weight: 600;
  cursor: help;
}

.backlinks-cell {
  display: flex;
  max-width: 240px;
  flex-direction: column;
  gap: 6px;
}

.backlink-item-row {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  width: 100%;
}

.title-cell strong,
.title-cell span,
.media-cell,
.backlink-anchor,
.error-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.media-cell {
  display: block;
  max-width: 96px;
}

.backlink-anchor {
  flex: 1;
  color: #ff1831;
  text-decoration: none;
  transition: color 0.2s ease;
  font-weight: 500;
  cursor: pointer;
}

.backlink-anchor:hover {
  color: #d41327;
  text-decoration: underline;
}

.copy-link-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  padding: 0;
  border: none;
  background: transparent;
  color: #94a3b8;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.copy-link-btn:hover {
  color: #ff1831;
  background: #fff4f4;
}

.title-cell span {
  cursor: help;
}

.title-cell span,
.muted {
  color: #667085;
  font-size: 12px;
}

.error-text {
  display: block;
  max-width: 240px;
  color: #e11d48;
  font-weight: 500;
}

@media (max-width: 720px) {
  .orders-toolbar {
    align-items: stretch;
    flex-direction: column;
  }

  .orders-toolbar-actions {
    align-items: stretch;
    flex-direction: column;
  }
}
</style>
