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

import KolPackageFormModal from '@/components/kol/KolPackageFormModal.vue'
import KolPlatformTags from '@/components/kol/KolPlatformTags.vue'
import KolPromptEditor from '@/components/kol/KolPromptEditor.vue'
import KolPromptFormModal from '@/components/kol/KolPromptFormModal.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 deletingPromptId = 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('kol.manage.messages.packageCreated'))
    void 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('kol.manage.messages.packageUpdated'))
    void 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.messages.packagePublished'))
    void queryClient.invalidateQueries({ queryKey: ['kol', 'packages'] })
  },
  onError: (error) => message.error(formatError(error)),
})

const archivePackageMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.archivePackage(id),
  onSuccess: () => {
    message.success(t('kol.manage.messages.packageArchived'))
    void queryClient.invalidateQueries({ queryKey: ['kol', 'packages'] })
  },
  onError: (error) => message.error(formatError(error)),
})

const selfSubscribePackageMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.selfSubscribePackage(id),
  onSuccess: () => {
    message.success('已订阅自己的订阅包')
    invalidateKolPackageAccess()
  },
  onError: (error) => message.error(formatError(error)),
})

const cancelSelfSubscriptionMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.cancelSelfSubscription(id),
  onSuccess: () => {
    message.success('已取消订阅自己的订阅包')
    invalidateKolPackageAccess()
  },
  onError: (error) => message.error(formatError(error)),
})

const deletePackageMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.deletePackage(id),
  onSuccess: (_, id) => {
    message.success(t('kol.manage.messages.packageDeleted'))
    void queryClient.invalidateQueries({ queryKey: ['kol', 'packages'] })
    if (selectedPackageId.value === id) {
      selectedPackageId.value = null
      editingPromptId.value = null
    }
  },
  onError: (error) => message.error(formatError(error)),
})

const createPromptMutation = useMutation({
  mutationFn: (body: CreateKolPromptRequest) =>
    kolManageApi.createPrompt(selectedPackageId.value!, body),
  onSuccess: () => {
    message.success(t('kol.manage.messages.promptCreated'))
    void 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.messages.promptActivated'
          : 'kol.manage.messages.promptArchived',
      ),
    )
    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 deletePromptMutation = useMutation({
  mutationFn: (id: number) => kolManageApi.deletePrompt(id),
  onMutate: (id) => {
    deletingPromptId.value = id
  },
  onSuccess: (_, id) => {
    message.success(t('kol.manage.messages.promptDeleted'))
    void queryClient.invalidateQueries({ queryKey: ['kol', 'packages'] })
    void queryClient.invalidateQueries({
      queryKey: ['kol', 'packages', selectedPackageId.value, 'prompts'],
    })
    void queryClient.invalidateQueries({ queryKey: ['kol', 'prompt', id] })
    if (editingPromptId.value === id) {
      editingPromptId.value = null
    }
  },
  onError: (error) => message.error(formatError(error)),
  onSettled: () => {
    deletingPromptId.value = null
  },
})

function invalidateKolPackageAccess() {
  void queryClient.invalidateQueries({ queryKey: ['kol', 'packages'] })
  void queryClient.invalidateQueries({ queryKey: ['kol', 'my-subscription-prompts'] })
  void queryClient.invalidateQueries({ queryKey: ['workspace'] })
}

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: t('kol.manage.confirmDeletePackage'),
    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 handleDeletePrompt(id: number) {
  Modal.confirm({
    title: t('common.delete') + '?',
    content: t('kol.manage.confirmDeletePrompt'),
    onOk: () => deletePromptMutation.mutate(id),
  })
}

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')
}

function packageStatusLabel(status: string) {
  if (status === 'published') return t('kol.manage.packageStatus.published')
  if (status === 'archived') return t('kol.manage.packageStatus.archived')
  return t('kol.manage.packageStatus.draft')
}

function isSelfSubscribed(pkg: KolPackageSummary) {
  return pkg.self_subscription?.status === 'active'
}

function canSelfSubscribe(pkg: KolPackageSummary) {
  return pkg.status === 'published' && !isSelfSubscribed(pkg)
}

function canCancelSelfSubscription(pkg: KolPackageSummary) {
  return pkg.self_subscription?.status === 'active'
}
</script>

<template>
  <div class="kol-manage-view">
    <section v-if="!editingPromptId" class="page-title-card">
      <div class="page-title-card__header">
        <div class="page-title-card__copy">
          <h2>{{ t('kol.manage.title') }}</h2>
          <p>{{ t('kol.manage.subtitle') }}</p>
        </div>
      </div>
    </section>

    <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>{{ t('kol.manage.packageTitle') }}</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">
          <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'
                        : item.status === 'archived'
                          ? 'orange'
                          : 'default'
                    "
                    size="small"
                  >
                    {{ packageStatusLabel(item.status) }}
                  </a-tag>
                  <a-tag v-if="isSelfSubscribed(item)" color="blue" size="small">自己已订阅</a-tag>
                  <span>{{ t('kol.marketplace.prompts', { count: 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-item
                        v-if="canSelfSubscribe(item)"
                        @click="selfSubscribePackageMutation.mutate(item.id)"
                      >
                        <CheckCircleOutlined />
                        订阅自己
                      </a-menu-item>
                      <a-menu-item
                        v-if="canCancelSelfSubscription(item)"
                        danger
                        @click="cancelSelfSubscriptionMutation.mutate(item.id)"
                      >
                        <StopOutlined />
                        取消订阅
                      </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>{{ t('kol.manage.promptTitle') }}</h3>
            <a-button type="primary" size="small" @click="promptModalOpen = true">
              <template #icon><PlusOutlined /></template>
              {{ t('kol.manage.createPrompt') }}
            </a-button>
          </div>

          <a-table
            class="modern-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: 156 },
            ]"
            :data-source="prompts"
            :loading="promptsPending"
            :pagination="false"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'platform_hint'">
                <KolPlatformTags
                  :value="record.platform_hint || t('kol.manage.platformHintDefault')"
                  :max="3"
                  size="small"
                />
              </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>
                  <a-tooltip :title="t('common.delete')">
                    <a-button
                      type="text"
                      shape="circle"
                      size="small"
                      class="action-btn action-delete"
                      :loading="
                        deletePromptMutation.isPending.value && deletingPromptId === record.id
                      "
                      @click="handleDeletePrompt(record.id)"
                    >
                      <DeleteOutlined />
                    </a-button>
                  </a-tooltip>
                </div>
              </template>
            </template>
          </a-table>
        </template>
        <div v-else class="empty-prompts">
          <a-empty :description="t('kol.manage.emptyPromptSelection')" />
        </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;
  gap: 20px;
  height: calc(100vh - 120px);
}

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

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

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

.package-column {
  width: 340px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow:
    0 1px 3px 0 rgba(0, 0, 0, 0.02),
    0 4px 8px -2px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f2f5;
  display: flex;
  flex-direction: column;
}

.prompt-column {
  flex: 1;
  background: #ffffff;
  border-radius: 12px;
  box-shadow:
    0 1px 3px 0 rgba(0, 0, 0, 0.02),
    0 4px 8px -2px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f2f5;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

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

.column-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #111827;
}

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

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

.package-name {
  font-weight: 600;
  font-size: 14px;
  color: #1f2937;
}

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

.ant-list-item {
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 8px;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all 0.2s ease;
}

.ant-list-item:last-child {
  margin-bottom: 0;
}

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

.ant-list-item.is-selected {
  background-color: #f0f7ff;
  border-color: #bae0ff;
}

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

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

/* Modern Enterprise Table Styles */
:deep(.modern-table) {
  padding: 24px;
}

:deep(.modern-table .ant-table-thead > tr > th) {
  background-color: #f9fafb !important;
  color: #4b5563;
  font-weight: 600;
  border-bottom: 1px solid #f3f4f6;
  padding: 12px 16px;
}

:deep(.modern-table .ant-table-tbody > tr > td) {
  padding: 16px;
  border-bottom: 1px solid #f3f4f6;
  color: #1f2937;
}

:deep(.modern-table .ant-table-tbody > tr:last-child > td) {
  border-bottom: none;
}

:deep(.modern-table .ant-table-tbody > tr:hover > td) {
  background-color: #f9fafb !important;
}

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

.action-btn {
  color: #6b7280;
  transition: all 0.2s;
}

.action-edit.ant-btn:hover:not(:disabled) {
  color: #059669;
  background: #d1fae5;
}

.action-enable.ant-btn:hover:not(:disabled) {
  color: #2563eb;
  background: #dbeafe;
}

.action-disable.ant-btn:hover:not(:disabled) {
  color: #d97706;
  background: #fef3c7;
}

.action-delete.ant-btn:hover:not(:disabled) {
  color: #dc2626;
  background: #fee2e2;
}
</style>
