<script setup lang="ts">
import { Ban, CheckCircle, Key, Plus, Users } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { Card } from '@/pages/admin/cards/data/schema'

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

const { t } = useI18n()

interface Application {
  id: number
  name: string
}

interface CardType {
  id: number
  name: string
  application_id: number
}

const router = useRouter()

const loading = ref(true)
const cards = ref<Card[]>([])
const tableRef = ref()
const applications = ref<Application[]>([])
const cardTypes = ref<CardType[]>([])

const appFilter = ref<string>('')
const cardTypeFilter = ref<string>('')
const statusFilter = ref<string>('')
const startDate = ref<string>('')
const endDate = ref<string>('')
const searchFilter = ref<string>('')

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

const filteredCardTypes = computed(() => {
  if (appFilter.value) {
    return cardTypes.value.filter(
      ct => String(ct.application_id) === appFilter.value,
    )
  }
  return cardTypes.value
})

const filteredCards = computed(() => {
  let result = cards.value

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

  if (cardTypeFilter.value) {
    result = result.filter(card => String(card.card_type_id) === cardTypeFilter.value)
  }

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

  if (startDate.value) {
    const fromDateTime = startDate.value.includes('T')
      ? startDate.value.replace('T', ' ')
      : `${startDate.value} 00:00`
    result = result.filter(card => card.created_at >= fromDateTime)
  }

  if (endDate.value) {
    const toDateTime = endDate.value.includes('T')
      ? endDate.value.replace('T', ' ')
      : `${endDate.value} 23:59`
    result = result.filter(card => card.created_at <= toDateTime)
  }

  if (searchFilter.value) {
    const search = searchFilter.value.toLowerCase()
    result = result.filter(card =>
      card.card_key?.toLowerCase().includes(search)
      || card.application?.name?.toLowerCase().includes(search)
      || card.card_type?.name?.toLowerCase().includes(search)
      || card.creator?.username?.toLowerCase().includes(search)
      || card.app_user?.username?.toLowerCase().includes(search),
    )
  }

  return result
})

const unusedCount = computed(() => filteredCards.value.filter(card => card.status === 'unused').length)
const usedCount = computed(() => filteredCards.value.filter(card => card.status === 'used').length)
const bannedCount = computed(() => filteredCards.value.filter(card => card.status === 'banned').length)

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

const cardTypeOptions = computed(() => {
  if (appFilter.value) {
    return filteredCardTypes.value.map(ct => ({
      label: ct.name,
      value: String(ct.id),
    }))
  }
  return []
})

const statusOptions = computed(() => [
  { label: t('admin.cards.unused'), value: 'unused' },
  { label: t('admin.cards.used'), value: 'used' },
  { label: t('admin.cards.banned'), value: 'banned' },
])

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

async function fetchCardTypes() {
  try {
    const data = await api.get<{ card_types: CardType[] }>('/dev/card-types')
    cardTypes.value = data?.card_types || []
  }
  catch (error) {
    console.error('获取卡类列表失败:', error)
  }
}

async function fetchCards() {
  loading.value = true
  try {
    const data = await api.get<Card[]>('/dev/cards')
    cards.value = Array.isArray(data) ? data : []
  }
  catch (error) {
    console.error('获取卡密列表失败:', error)
    cards.value = []
  }
  finally {
    loading.value = false
  }
}

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

async function toggleStatus(card: Card) {
  try {
    const newStatus = card.status === 'banned' ? 'unused' : 'banned'
    await api.put(`/dev/cards/${card.id}/status`, { status: newStatus })
    toast.success(t('admin.cards.statusUpdateSuccess'))
    fetchCards()
  }
  catch (error: any) {
    console.error('切换卡密状态失败:', error)
    toast.error(error.message || t('admin.cards.statusUpdateFailed'))
  }
}

function confirmDeleteCard(card: Card) {
  deleteTarget.value = card
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/cards/${deleteTarget.value.id}`)
    toast.success(t('admin.cards.deleteSuccess'))
    fetchCards()
  }
  catch (error: any) {
    console.error('删除卡密失败:', error)
    toast.error(error.message || t('admin.cards.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

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

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

async function batchToggleStatus(ids: (string | number)[], status: string) {
  try {
    await api.put('/dev/cards/batch/status', { ids, status })
    toast.success(t('admin.cards.batchUpdateSuccess'))
    fetchCards()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || t('admin.cards.batchUpdateFailed'))
  }
}

function handleExport() {
  const token = localStorage.getItem('token')
  const params = new URLSearchParams()
  if (appFilter.value)
    params.append('application_id', appFilter.value)
  if (cardTypeFilter.value)
    params.append('card_type_id', cardTypeFilter.value)
  if (startDate.value) {
    const startDateOnly = startDate.value.includes('T') ? startDate.value.split('T')[0] : startDate.value
    params.append('start_date', startDateOnly)
  }
  if (endDate.value) {
    const endDateOnly = endDate.value.includes('T') ? endDate.value.split('T')[0] : endDate.value
    params.append('end_date', endDateOnly)
  }

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

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

watch(() => appFilter.value, () => {
  cardTypeFilter.value = ''
})

onMounted(() => {
  fetchApplications()
  fetchCardTypes()
  fetchCards()
})
</script>

<template>
  <BasicPage
    :title="t('admin.cards.title')"
    :description="t('admin.cards.description')"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.cards.generateCard') }}
      </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.cards.totalCards') }}
            </UiCardTitle>
            <Key class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredCards.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.cards.unused') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ unusedCount }}
            </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.cards.used') }}
            </UiCardTitle>
            <Users class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ usedCount }}
            </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.cards.banned') }}
            </UiCardTitle>
            <Ban class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ bannedCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredCards"
            :on-toggle-status="toggleStatus"
            :on-delete="confirmDeleteCard"
            :search-filter="searchFilter"
            @refresh="fetchCards"
            @batch-disable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'unused').map((r: any) => r.original.id) || [], 'banned')"
            @batch-enable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'banned').map((r: any) => r.original.id) || [], 'unused')"
            @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) || [])"
            @export="handleExport"
            @update:search-filter="searchFilter = $event"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.cards.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="cardTypeFilter"
                :title="t('admin.cards.cardType')"
                :options="cardTypeOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.cards.status')"
                :options="statusOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="startDate"
                v-model:end-model-value="endDate"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('admin.cards.delete')"
      :cancel-button-text="t('admin.cards.create.cancelBtn')"
      @confirm="handleDeleteCard"
    >
      <template #title>
        {{ t('admin.cards.deleteCard') }}
      </template>
      <template #description>
        {{ t('admin.cards.deleteCardConfirm', { cardKey: deleteTarget?.card_key }) }}
      </template>
    </ConfirmDialog>

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