<script setup lang="ts">
import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
import { message, Modal } from "ant-design-vue";
import {
  PlusOutlined,
  EditOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  CloudUploadOutlined,
  InboxOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";

import KolPackageFormModal from "@/components/kol/KolPackageFormModal.vue";
import KolPromptFormModal from "@/components/kol/KolPromptFormModal.vue";
import KolPromptEditor from "@/components/kol/KolPromptEditor.vue";
import { kolManageApi } from "@/lib/api";
import { formatError } from "@/lib/errors";
import type { CreateKolPackageRequest, CreateKolPromptRequest, KolPackageSummary } from "@geo/shared-types";

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

const selectedPackageId = ref<number | null>(null);
const packageModalOpen = ref(false);
const editingPackage = ref<KolPackageSummary | null>(null);
const promptModalOpen = ref(false);
const editingPromptId = ref<number | null>(null);
const togglingPromptId = ref<number | null>(null);

const { data: packages, isPending: packagesPending } = useQuery({
  queryKey: ["kol", "packages"],
  queryFn: () => kolManageApi.listPackages(),
});

const { data: prompts, isPending: promptsPending } = useQuery({
  queryKey: computed(() => ["kol", "packages", selectedPackageId.value, "prompts"]),
  queryFn: () => kolManageApi.listPrompts(selectedPackageId.value!),
  enabled: computed(() => !!selectedPackageId.value),
});

const createPackageMutation = useMutation({
  mutationFn: (body: CreateKolPackageRequest) => kolManageApi.createPackage(body),
  onSuccess: () => {
    message.success(t("common.create") + "成功");
    queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
  },
  onError: (error) => message.error(formatError(error)),
});

const updatePackageMutation = useMutation({
  mutationFn: (data: { id: number; body: CreateKolPackageRequest }) =>
    kolManageApi.updatePackage(data.id, data.body),
  onSuccess: () => {
    message.success(t("common.edit") + "成功");
    queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
  },
  onError: (error) => message.error(formatError(error)),
});

const publishPackageMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.publishPackage(id),
  onSuccess: () => {
    message.success(t("kol.manage.publishPackage") + "成功");
    queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
  },
});

const archivePackageMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.archivePackage(id),
  onSuccess: () => {
    message.success(t("kol.manage.archivePackage") + "成功");
    queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
  },
});

const deletePackageMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.deletePackage(id),
  onSuccess: (_, id) => {
    message.success(t("common.delete") + "成功");
    queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
    if (selectedPackageId.value === id) {
      selectedPackageId.value = null;
      editingPromptId.value = null;
    }
  },
});

const createPromptMutation = useMutation({
  mutationFn: (body: CreateKolPromptRequest) =>
    kolManageApi.createPrompt(selectedPackageId.value!, body),
  onSuccess: () => {
    message.success(t("kol.manage.createPrompt") + "成功");
    queryClient.invalidateQueries({
      queryKey: ["kol", "packages", selectedPackageId.value, "prompts"],
    });
  },
  onError: (error) => message.error(formatError(error)),
});

const togglePromptStatusMutation = useMutation({
  mutationFn: (data: { id: number; nextStatus: "active" | "archived" }) =>
    data.nextStatus === "active"
      ? kolManageApi.activatePrompt(data.id)
      : kolManageApi.archivePrompt(data.id),
  onMutate: (variables) => {
    togglingPromptId.value = variables.id;
  },
  onSuccess: (_, variables) => {
    message.success(
      t(variables.nextStatus === "active" ? "kol.manage.activatePrompt" : "kol.manage.archivePrompt") + "成功"
    );
    void queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
    void queryClient.invalidateQueries({
      queryKey: ["kol", "packages", selectedPackageId.value, "prompts"],
    });
    void queryClient.invalidateQueries({ queryKey: ["kol", "prompt", variables.id] });
  },
  onError: (error) => message.error(formatError(error)),
  onSettled: () => {
    togglingPromptId.value = null;
  },
});

const packageInitialValue = computed<Partial<CreateKolPackageRequest> | undefined>(() => {
  if (!editingPackage.value) return undefined;
  return {
    name: editingPackage.value.name,
    description: editingPackage.value.description ?? undefined,
    industry: editingPackage.value.industry ?? undefined,
    tags: editingPackage.value.tags,
    price_note: editingPackage.value.price_note ?? undefined,
    cover_url: editingPackage.value.cover_url ?? undefined,
  };
});

function handleCreatePackage() {
  editingPackage.value = null;
  packageModalOpen.value = true;
}

function handleEditPackage(pkg: KolPackageSummary) {
  editingPackage.value = pkg;
  packageModalOpen.value = true;
}

function handlePackageSubmit(body: CreateKolPackageRequest) {
  if (editingPackage.value) {
    updatePackageMutation.mutate({ id: editingPackage.value.id, body });
  } else {
    createPackageMutation.mutate(body);
  }
}

function handleDeletePackage(id: number) {
  Modal.confirm({
    title: t("common.delete") + "?",
    content: "确定要删除这个订阅包吗？",
    onOk: () => deletePackageMutation.mutate(id),
  });
}

function handleSelectPackage(packageId: number) {
  selectedPackageId.value = packageId;
  editingPromptId.value = null;
}

function handleOpenEditor(promptId: number) {
  editingPromptId.value = promptId;
}

function handleCloseEditor() {
  editingPromptId.value = null;
}

function promptStatusLabel(status: string) {
  if (status === "active") return t("kol.manage.status.active");
  if (status === "archived") return t("kol.manage.status.archived");
  return t("kol.manage.status.draft");
}
</script>

<template>
  <div class="kol-manage-view">
    <div v-if="editingPromptId" class="manage-content manage-content--editor">
      <div class="fullscreen-editor">
        <KolPromptEditor :prompt-id="editingPromptId" @back="handleCloseEditor" />
      </div>
    </div>
    <div v-else class="manage-content">
        <div class="package-column">
          <div class="column-header">
            <h3>订阅包</h3>
            <a-button type="primary" size="small" @click="handleCreatePackage">
              <template #icon><PlusOutlined /></template>
              {{ t('kol.manage.createPackage') }}
            </a-button>
          </div>

          <a-list
            class="package-list"
            :loading="packagesPending"
            :data-source="packages"
            size="small"
          >
            <template #renderItem="{ item }">
              <a-list-item
                :class="{ 'is-selected': selectedPackageId === item.id }"
                @click="handleSelectPackage(item.id)"
              >
                <div class="package-item-content">
                  <div class="package-name">{{ item.name }}</div>
                  <div class="package-meta">
                    <a-tag :color="item.status === 'published' ? 'green' : 'orange'" size="small">
                      {{ item.status }}
                    </a-tag>
                    <span>{{ item.prompt_count }} 提示词</span>
                  </div>
                </div>
                <template #actions>
                  <a-dropdown>
                    <a class="ant-dropdown-link" @click.prevent>...</a>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item @click="handleEditPackage(item)">
                          <EditOutlined /> {{ t('common.edit') }}
                        </a-menu-item>
                        <a-menu-item
                          v-if="item.status !== 'published'"
                          @click="publishPackageMutation.mutate(item.id)"
                        >
                          <CloudUploadOutlined /> {{ t('kol.manage.publishPackage') }}
                        </a-menu-item>
                        <a-menu-item
                          v-if="item.status === 'published'"
                          @click="archivePackageMutation.mutate(item.id)"
                        >
                          <InboxOutlined /> {{ t('kol.manage.archivePackage') }}
                        </a-menu-item>
                        <a-menu-divider />
                        <a-menu-item danger @click="handleDeletePackage(item.id)">
                          <DeleteOutlined /> {{ t('common.delete') }}
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </div>

        <!-- Right Column: Prompts -->
        <div class="prompt-column">
          <template v-if="selectedPackageId">
            <div class="column-header">
              <h3>提示词</h3>
              <a-button type="primary" size="small" @click="promptModalOpen = true">
                <template #icon><PlusOutlined /></template>
                {{ t('kol.manage.createPrompt') }}
              </a-button>
            </div>

            <a-table
              :columns="[
                { title: t('common.title'), dataIndex: 'name', key: 'name' },
                { title: t('tracking.columns.platform'), dataIndex: 'platform_hint', key: 'platform_hint' },
                { title: t('common.status'), dataIndex: 'status', key: 'status' },
                { title: t('common.actions'), key: 'actions', align: 'right', width: 112 },
              ]"
              :data-source="prompts"
              :loading="promptsPending"
              size="small"
              :pagination="false"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'platform_hint'">
                  <a-tag color="blue">{{ record.platform_hint || '通用' }}</a-tag>
                </template>
                <template v-else-if="column.key === 'status'">
                  <a-tag :color="record.status === 'active' ? 'green' : record.status === 'archived' ? 'orange' : 'default'">
                    {{ promptStatusLabel(record.status) }}
                  </a-tag>
                </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="handleOpenEditor(record.id)"
                      >
                        <EditOutlined />
                      </a-button>
                    </a-tooltip>
                    <a-tooltip
                      :title="record.status === 'active' ? t('kol.manage.archivePrompt') : t('kol.manage.activatePrompt')"
                    >
                      <a-button
                        type="text"
                        shape="circle"
                        size="small"
                        :class="[
                          'action-btn',
                          record.status === 'active' ? 'action-disable' : 'action-enable',
                        ]"
                        :loading="togglePromptStatusMutation.isPending.value && togglingPromptId === record.id"
                        @click="togglePromptStatusMutation.mutate({
                          id: record.id,
                          nextStatus: record.status === 'active' ? 'archived' : 'active',
                        })"
                      >
                        <PauseCircleOutlined v-if="record.status === 'active'" />
                        <PlayCircleOutlined v-else />
                      </a-button>
                    </a-tooltip>
                  </div>
                </template>
              </template>
            </a-table>
          </template>
          <div v-else class="empty-prompts">
            <a-empty description="请选择左侧订阅包以查看提示词" />
          </div>
        </div>
      </div>

    <KolPackageFormModal
      v-model:open="packageModalOpen"
      :initial-value="packageInitialValue"
      @submit="handlePackageSubmit"
    />

    <KolPromptFormModal
      v-model:open="promptModalOpen"
      :package-id="selectedPackageId || 0"
      @submit="createPromptMutation.mutate"
    />
  </div>
</template>

<style scoped>
.kol-manage-view {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 64px);
}

.fullscreen-editor {
  flex: 1;
  min-height: 0;
  border-radius: 12px;
  overflow: hidden;
}

.manage-content--editor {
  padding: 16px;
}

.manage-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  padding: 16px;
  gap: 16px;
}

.package-column {
  width: 320px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.prompt-column {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.column-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.column-header h3 {
  margin: 0;
  font-size: 16px;
}

.package-list {
  flex: 1;
  overflow-y: auto;
}

.package-item-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.package-name {
  font-weight: 500;
}

.package-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #8c8c8c;
}

.ant-list-item.is-selected {
  background-color: #e6f7ff;
}

.ant-list-item {
  cursor: pointer;
  transition: background-color 0.3s;
}

.ant-list-item:hover {
  background-color: #fafafa;
}

.empty-prompts {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.prompt-editor-panel {
  flex: 1;
  min-height: 0;
}

.table-actions-row {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.action-edit.ant-btn:hover:not(:disabled) {
  color: #52c41a;
  background: #f6ffed;
}

.action-enable.ant-btn:hover:not(:disabled) {
  color: #1677ff;
  background: #e6f4ff;
}

.action-disable.ant-btn:hover:not(:disabled) {
  color: #fa8c16;
  background: #fff7e6;
}
</style>
