<script setup lang="ts">
import { LoadingOutlined, EyeOutlined } from "@ant-design/icons-vue";
import { useQuery } from "@tanstack/vue-query";
import { type TableColumnsType } from "ant-design-vue";
import type { InstantTaskItem, InstantTaskListParams } from "@geo/shared-types";
import type { Dayjs } from "dayjs";
import { computed, onBeforeUnmount, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";

import ArticleDetailDrawer from "@/components/ArticleDetailDrawer.vue";
import { instantTasksApi, promptRulesApi } from "@/lib/api";
import { formatDateTime, getGenerateStatusMeta } from "@/lib/display";
import { formatPublishPlatformList } from "@/lib/publish-platforms";

const { t } = useI18n();

const page = ref(1);
const pageSize = ref(20);
const createdRange = ref<[Dayjs, Dayjs] | null>(null);
const detailOpen = ref(false);
const selectedArticleId = ref<number | null>(null);

const draftFilters = reactive<{
  prompt_rule_id?: number;
  status?: string;
  keyword?: string;
}>({
  keyword: "",
});

const appliedFilters = reactive<{
  prompt_rule_id?: number;
  status?: string;
  keyword?: string;
  created_from?: string;
  created_to?: string;
}>({
  keyword: "",
});

const rulesQuery = useQuery({
  queryKey: ["promptRules", "simple"],
  queryFn: () => promptRulesApi.listSimple(),
});

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

const statusOptions = computed(() => [
  { label: getGenerateStatusMeta("queued").label, value: "queued" },
  { label: getGenerateStatusMeta("running").label, value: "running" },
  { label: getGenerateStatusMeta("completed").label, value: "completed" },
  { label: getGenerateStatusMeta("failed").label, value: "failed" },
]);

const listParams = computed<InstantTaskListParams>(() => {
  const params: InstantTaskListParams = {
    page: page.value,
    page_size: pageSize.value,
  };
  if (appliedFilters.prompt_rule_id) params.prompt_rule_id = appliedFilters.prompt_rule_id;
  if (appliedFilters.status) params.status = appliedFilters.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(() => ["instantTasks", "list", listParams.value]),
  queryFn: () => instantTasksApi.list(listParams.value),
});

const columns = computed<TableColumnsType<InstantTaskItem>>(() => [
  { title: t("custom.instant.name"), dataIndex: "name", key: "name", width: 220 },
  { title: t("custom.schedule.rule"), dataIndex: "prompt_rule_name", key: "prompt_rule_name", width: 180 },
  { title: t("custom.instant.executionStatus"), dataIndex: "status", key: "status", width: 140 },
  { title: t("custom.instant.executionTime"), dataIndex: "execution_time", key: "execution_time", width: 170 },
  { title: t("custom.schedule.autoPublishPlatforms"), dataIndex: "auto_publish_platforms", key: "auto_publish_platforms", width: 220 },
  { title: t("custom.task.generateCount"), dataIndex: "generate_count", key: "generate_count", width: 120 },
  { title: t("custom.instant.createdTime"), dataIndex: "created_at", key: "created_at", width: 170 },
  { title: t("common.actions"), key: "actions", width: 88, fixed: "right", align: "right" },
]);

let pollingTimer: number | null = null;

function applyFilters(): void {
  page.value = 1;
  appliedFilters.prompt_rule_id = draftFilters.prompt_rule_id;
  appliedFilters.status = draftFilters.status;
  appliedFilters.keyword = draftFilters.keyword?.trim() || "";
  appliedFilters.created_from = createdRange.value?.[0]?.startOf("day").toISOString();
  appliedFilters.created_to = createdRange.value?.[1]?.endOf("day").toISOString();
}

function resetFilters(): void {
  draftFilters.prompt_rule_id = undefined;
  draftFilters.status = undefined;
  draftFilters.keyword = "";
  createdRange.value = null;
  applyFilters();
}

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

function openArticle(task: InstantTaskItem): void {
  if (!task.article_id) {
    return;
  }
  selectedArticleId.value = task.article_id;
  detailOpen.value = true;
}

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;
}

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

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

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

      <div class="task-tab__filter">
        <label>{{ t("custom.filters.status") }}:</label>
        <a-select
          v-model:value="draftFilters.status"
          allow-clear
          size="large"
          :options="statusOptions"
          :placeholder="t('common.selectPlease')"
          @change="applyFilters"
        />
      </div>

      <div class="task-tab__filter task-tab__filter--range">
        <label>{{ t("custom.filters.createdTime") }}:</label>
        <a-range-picker
          v-model:value="createdRange"
          allow-clear
          size="large"
          format="YYYY-MM-DD"
          @change="applyFilters"
        />
      </div>

      <div class="task-tab__filter task-tab__filter--keyword">
        <label>{{ t("custom.filters.name") }}:</label>
        <a-input-search
          v-model:value="draftFilters.keyword"
          size="large"
          :placeholder="t('custom.filters.namePlaceholder')"
          @search="applyFilters"
          @pressEnter="applyFilters"
        />
      </div>

      <div class="task-tab__filter task-tab__filter--action">
        <a-button size="large" @click="resetFilters">{{ t("common.reset") }}</a-button>
      </div>
    </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"
      :scroll="{ x: 1280 }"
      @change="(p: any) => handleTableChange(p.current, p.pageSize)"
    >
      <template #emptyText>{{ t("custom.instant.empty") }}</template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'prompt_rule_name'">
          {{ record.prompt_rule_name || "--" }}
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="getGenerateStatusMeta(record.status).color">
            <span class="task-tab__status">
              <LoadingOutlined v-if="record.status === 'queued' || record.status === 'running'" spin />
              <span>{{ getGenerateStatusMeta(record.status).label }}</span>
            </span>
          </a-tag>
        </template>
        <template v-else-if="column.key === 'execution_time'">
          {{ formatDateTime(record.execution_time) }}
        </template>
        <template v-else-if="column.key === 'auto_publish_platforms'">
          {{ formatPublishPlatformList(record.auto_publish_platforms) }}
        </template>
        <template v-else-if="column.key === 'generate_count'">
          {{ record.generate_count || 1 }}
        </template>
        <template v-else-if="column.key === 'created_at'">
          {{ formatDateTime(record.created_at) }}
        </template>
        <template v-else-if="column.key === 'actions'">
          <div class="table-actions-row">
            <a-tooltip :title="t('common.preview')">
              <span>
                <a-button
                  type="text"
                  shape="circle"
                  size="small"
                  class="action-btn action-eye"
                  :disabled="!record.article_id"
                  @click="openArticle(record)"
                >
                  <EyeOutlined />
                </a-button>
              </span>
            </a-tooltip>
          </div>
        </template>
      </template>
    </a-table>

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

<style scoped>
.task-tab__filters {
  display: grid;
  grid-template-columns: minmax(180px, 240px) minmax(180px, 240px) minmax(240px, 320px) minmax(240px, 1fr) auto;
  gap: 16px;
  margin-bottom: 18px;
}

.task-tab__filter {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-tab__filter label {
  flex-shrink: 0;
  color: #434343;
  font-size: 14px;
  white-space: nowrap;
}

.task-tab__filter :deep(.ant-select),
.task-tab__filter :deep(.ant-picker),
.task-tab__filter :deep(.ant-input-search) {
  width: 100%;
}

.task-tab__filter--action {
  justify-content: flex-end;
}

.task-tab__status {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

@media (max-width: 1400px) {
  .task-tab__filters {
    grid-template-columns: repeat(2, minmax(260px, 1fr));
  }

  .task-tab__filter--action {
    justify-content: flex-start;
  }
}

@media (max-width: 900px) {
  .task-tab__filters {
    grid-template-columns: 1fr;
  }
}
</style>
