<script setup lang="ts">
import {
  DeleteOutlined,
  EditOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
} from "@ant-design/icons-vue";
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
import { message, type TableColumnsType } from "ant-design-vue";
import type { ScheduleTask, ScheduleTaskListParams } from "@geo/shared-types";
import type { Dayjs } from "dayjs";
import { computed, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";

import ScheduleTaskModal from "@/components/ScheduleTaskModal.vue";
import { promptRulesApi, schedulesApi } from "@/lib/api";
import { formatCronExecutionTime, formatDateTime } from "@/lib/display";
import { formatError } from "@/lib/errors";

const queryClient = useQueryClient();
const { t } = useI18n();

const modalOpen = ref(false);
const editingTask = ref<ScheduleTask | null>(null);
const page = ref(1);
const pageSize = ref(20);
const createdRange = ref<[Dayjs, Dayjs] | 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: t("custom.schedule.enabled"), value: "enabled" },
  { label: t("custom.schedule.disabled"), value: "disabled" },
]);

const listParams = computed<ScheduleTaskListParams>(() => {
  const params: ScheduleTaskListParams = {
    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(() => ["schedules", "list", listParams.value]),
  queryFn: () => schedulesApi.list(listParams.value),
});

const columns = computed<TableColumnsType<ScheduleTask>>(() => [
  { title: t("custom.schedule.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: "cron_expr", key: "cron_expr", width: 170 },
  { title: t("custom.schedule.autoPublish"), dataIndex: "auto_publish", key: "auto_publish", width: 160 },
  { 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: 140, fixed: "right", align: "right" },
]);

const removeMutation = useMutation({
  mutationFn: (id: number) => schedulesApi.remove(id),
  onSuccess: async () => {
    message.success(t("custom.messages.scheduleDeleted"));
    await queryClient.invalidateQueries({ queryKey: ["schedules"] });
  },
  onError: (error) => message.error(formatError(error)),
});

const toggleStatusMutation = useMutation({
  mutationFn: ({ id, status }: { id: number; status: "enabled" | "disabled" }) =>
    schedulesApi.toggleStatus(id, { status }),
  onSuccess: async (_data, variables) => {
    message.success(
      variables.status === "enabled"
        ? t("custom.messages.scheduleEnabled")
        : t("custom.messages.scheduleDisabled"),
    );
    await queryClient.invalidateQueries({ queryKey: ["schedules"] });
  },
  onError: (error) => message.error(formatError(error)),
});

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 openModal(task?: ScheduleTask): void {
  editingTask.value = task ?? null;
  modalOpen.value = true;
}

function handleTableChange(nextPage: number, nextPageSize: number): void {
  page.value = nextPage;
  pageSize.value = nextPageSize;
}
</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: 1360 }"
      @change="(p: any) => handleTableChange(p.current, p.pageSize)"
    >
      <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="record.status === 'enabled' ? 'green' : 'default'">
            {{ record.status === "enabled" ? t("custom.schedule.enabled") : t("custom.schedule.disabled") }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'cron_expr'">
          {{ formatCronExecutionTime(record.cron_expr) }}
        </template>
        <template v-else-if="column.key === 'auto_publish'">
          <a-tag :color="record.auto_publish ? 'blue' : 'default'">
            {{
              record.auto_publish
                ? t("custom.schedule.autoPublishAccountCount", { count: record.publish_account_ids?.length ?? 0 })
                : t("custom.schedule.manualPublish")
            }}
          </a-tag>
        </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.edit')">
              <a-button
                type="text"
                shape="circle"
                size="small"
                class="action-btn action-edit"
                @click="openModal(record)"
              >
                <EditOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip
              :title="record.status === 'enabled' ? t('custom.schedule.disabled') : t('custom.schedule.enabled')"
            >
              <a-button
                type="text"
                shape="circle"
                size="small"
                :class="[
                  'action-btn',
                  record.status === 'enabled' ? 'action-disable' : 'action-enable',
                ]"
                @click="toggleStatusMutation.mutate({
                  id: record.id,
                  status: record.status === 'enabled' ? 'disabled' : 'enabled',
                })"
              >
                <PauseCircleOutlined v-if="record.status === 'enabled'" />
                <PlayCircleOutlined v-else />
              </a-button>
            </a-tooltip>
            <a-popconfirm
              :title="t('custom.schedule.deleteConfirm')"
              @confirm="removeMutation.mutate(record.id)"
            >
              <a-button
                type="text"
                shape="circle"
                size="small"
                class="action-btn action-delete"
                :title="t('common.delete')"
              >
                <DeleteOutlined />
              </a-button>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>

    <ScheduleTaskModal v-model:open="modalOpen" :task="editingTask" />
  </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;
}

@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>
