<script setup lang="ts">
import { CheckCircle, Megaphone, Pin, Plus, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { Announcement } from '@/pages/admin/announcements/data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/announcements/components/data-table.vue'
import api, { BASE_URL } from '@/services/api'

const { t } = useI18n()

interface Application {
  id: number
  name: string
}

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const announcements = ref<Announcement[]>([])
const applications = ref<Application[]>([])
const tableRef = ref()

const appFilter = ref<string>('')
const typeFilter = ref<string>('')
const statusFilter = ref<string>('')
const searchFilter = ref<string>('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<Announcement | null>(null)
const batchDeleteDialogOpen = ref(false)
const batchDeleteIds = ref<number[]>([])

const applicationOptions = computed(() => {
  return applications.value.map(app => ({
    label: app.name,
    value: String(app.id),
  }))
})

const typeOptions = computed(() => [
  { label: t('admin.announcements.types.info'), value: 'info' },
  { label: t('admin.announcements.types.warning'), value: 'warning' },
  { label: t('admin.announcements.types.error'), value: 'error' },
  { label: t('admin.announcements.types.success'), value: 'success' },
])

const statusOptions = computed(() => [
  { label: t('admin.announcements.statuses.active'), value: 'active' },
  { label: t('admin.announcements.statuses.inactive'), value: 'inactive' },
])

const filteredAnnouncements = computed(() => {
  let result = announcements.value

  if (appFilter.value) {
    result = result.filter(a => String(a.application_id) === appFilter.value)
  }

  if (typeFilter.value) {
    result = result.filter(a => a.type === typeFilter.value)
  }

  if (statusFilter.value) {
    result = result.filter(a => a.status === statusFilter.value)
  }

  if (searchFilter.value) {
    const search = searchFilter.value.toLowerCase()
    result = result.filter(a =>
      a.title?.toLowerCase().includes(search)
      || a.content?.toLowerCase().includes(search)
      || a.application_name?.toLowerCase().includes(search),
    )
  }

  return result
})

const activeCount = computed(() => filteredAnnouncements.value.filter(a => a.status === 'active').length)
const inactiveCount = computed(() => filteredAnnouncements.value.filter(a => a.status === 'inactive').length)
const topCount = computed(() => filteredAnnouncements.value.filter(a => a.is_top).length)

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

async function fetchAnnouncements() {
  loading.value = true
  try {
    const data = await api.get<{ announcements: Announcement[], total: number }>('/dev/announcements')
    announcements.value = data?.announcements || []
  }
  catch (error) {
    console.error('加载公告失败:', error)
    announcements.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/announcements/create')
}

function goToEdit(announcement: Announcement) {
  router.push(`/admin/announcements/${announcement.id}`)
}

async function toggleTop(announcement: Announcement) {
  try {
    await api.put(`/dev/applications/${announcement.application_id}/announcements/${announcement.id}/top`)
    toast.success(announcement.is_top ? t('admin.announcements.unpinned') : t('admin.announcements.pinned'))
    fetchAnnouncements()
  }
  catch (error: any) {
    console.error('切换置顶失败:', error)
    toast.error(error.message || t('common.error'))
  }
}

function confirmDelete(announcement: Announcement) {
  deleteTarget.value = announcement
  deleteDialogOpen.value = true
}

async function handleDelete() {
  if (!deleteTarget.value)
    return

  try {
    await api.delete(`/dev/applications/${deleteTarget.value.application_id}/announcements/${deleteTarget.value.id}`)
    toast.success(t('admin.announcements.deleteSuccess'))
    fetchAnnouncements()
  }
  catch (error: any) {
    console.error('删除公告失败:', error)
    toast.error(error.message || t('common.error'))
  }
  finally {
    deleteTarget.value = null
  }
}

function handleExport() {
  const token = localStorage.getItem('token')
  const params = new URLSearchParams()
  if (appFilter.value)
    params.append('application_id', appFilter.value)
  if (typeFilter.value)
    params.append('type', typeFilter.value)
  if (statusFilter.value)
    params.append('status', statusFilter.value)

  const queryString = params.toString()
  const url = `${BASE_URL}/dev/announcements/export?${queryString}&token=${token}`
  window.open(url, '_blank')
}

function handleBatchExport(ids: number[]) {
  if (!ids.length)
    return
  const token = localStorage.getItem('token')
  const params = new URLSearchParams()
  params.append('ids', ids.join(','))
  const url = `${BASE_URL}/dev/announcements/export?${params.toString()}&token=${token}`
  window.open(url, '_blank')
}

function confirmBatchDelete(ids: number[]) {
  batchDeleteIds.value = ids
  batchDeleteDialogOpen.value = true
}

async function handleBatchDelete() {
  try {
    await api.delete('/dev/announcements/batch', { ids: batchDeleteIds.value } as any)
    toast.success(t('admin.announcements.batchDeleteSuccess'))
    fetchAnnouncements()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || t('common.error'))
  }
  finally {
    batchDeleteIds.value = []
  }
}

onMounted(() => {
  fetchApplications()
  fetchAnnouncements()
  const appParam = route.query.app as string
  if (appParam) {
    appFilter.value = appParam
  }
})
</script>

<template>
  <BasicPage
    :title="t('admin.announcements.title')"
    :description="t('admin.announcements.description')"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.announcements.create') }}
      </UiButton>
    </template>

    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.announcements.totalAnnouncements') }}
            </UiCardTitle>
            <Megaphone class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredAnnouncements.length }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.announcements.activeCount') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.announcements.inactiveCount') }}
            </UiCardTitle>
            <XCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ inactiveCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.announcements.topCount') }}
            </UiCardTitle>
            <Pin class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ topCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredAnnouncements"
            :on-toggle-top="toggleTop"
            :on-edit="goToEdit"
            :on-delete="confirmDelete"
            :search-filter="searchFilter"
            @refresh="fetchAnnouncements"
            @update:search-filter="searchFilter = $event"
            @export="handleExport"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
            @batch-export="handleBatchExport(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.announcements.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="typeFilter"
                :title="t('admin.announcements.type')"
                :options="typeOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.announcements.status')"
                :options="statusOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('common.delete')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleDelete"
    >
      <template #title>
        {{ t('admin.announcements.deleteAnnouncement') }}
      </template>
      <template #description>
        {{ t('admin.announcements.deleteConfirm', { title: deleteTarget?.title }) }}
      </template>
    </ConfirmDialog>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      :confirm-button-text="t('common.delete')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleBatchDelete"
    >
      <template #title>
        {{ t('admin.announcements.batchDelete') }}
      </template>
      <template #description>
        {{ t('admin.announcements.batchDeleteConfirm', { count: batchDeleteIds.length }) }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
