<script setup lang="ts">
import { 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 type { Card } from '@/pages/agent/cards/data/schema'

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/agent/cards/components/data-table.vue'
import api, { BASE_URL } from '@/services/api'

const { t } = useI18n()
const router = useRouter()

interface Application {
  id: number
  name: string
}

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

const loading = ref(true)
const cards = ref<Card[]>([])
const total = ref(0)
const unusedCount = ref(0)
const usedCount = ref(0)
const expiredCount = ref(0)
const bannedCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
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 filteredCardTypes = computed(() => {
  if (appFilter.value) {
    return cardTypes.value.filter(
      ct => String(ct.application_id) === appFilter.value,
    )
  }
  return cardTypes.value
})

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

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

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

const serverPagination = computed(() => ({
  page: currentPage.value,
  pageSize: pageSize.value,
  total: total.value,
  onPageChange: (page: number) => {
    currentPage.value = page
    fetchCards()
  },
  onPageSizeChange: (size: number) => {
    pageSize.value = size
    currentPage.value = 1
    fetchCards()
  },
}))

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

async function fetchCardTypes() {
  try {
    for (const app of applications.value) {
      const data = await api.get<{ cardTypes: CardType[] }>(`/agent/apps/${app.id}`)
      const types = data?.cardTypes || []
      for (const ct of types) {
        if (!cardTypes.value.some(existing => existing.id === ct.id)) {
          cardTypes.value.push({ ...ct, application_id: app.id })
        }
      }
    }
  }
  catch (error) {
    console.error('获取卡类列表失败:', error)
  }
}

async function fetchCards() {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', String(currentPage.value))
    params.append('page_size', String(pageSize.value))

    if (appFilter.value) {
      params.append('application_id', appFilter.value)
    }
    if (cardTypeFilter.value) {
      params.append('card_type_id', cardTypeFilter.value)
    }
    if (statusFilter.value) {
      params.append('status', statusFilter.value)
    }
    if (startDate.value) {
      params.append('start_date', startDate.value.split('T')[0])
    }
    if (endDate.value) {
      params.append('end_date', endDate.value.split('T')[0])
    }
    if (searchFilter.value) {
      params.append('search', searchFilter.value.trim())
    }

    const data = await api.get<any>(`/agent/cards?${params.toString()}`)
    if (data?.cards) {
      cards.value = data.cards
      total.value = data.filtered_total || data.total || data.cards.length
      unusedCount.value = data.unused_count || 0
      usedCount.value = data.used_count || 0
      expiredCount.value = data.expired_count || 0
      bannedCount.value = data.banned_count || data.disabled_count || 0
    } else if (Array.isArray(data)) {
      cards.value = data
      total.value = data.length
    } else {
      cards.value = []
      total.value = 0
    }
  }
  catch (error) {
    console.error('Load cards failed:', error)
    cards.value = []
    total.value = 0
  }
  finally {
    loading.value = false
  }
}

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

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 (statusFilter.value)
    params.append('status', statusFilter.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}/agent/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}/agent/cards/export?${params.toString()}&token=${token}`
  window.open(url, '_blank')
}

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

watch([appFilter, cardTypeFilter, statusFilter, startDate, endDate, searchFilter], () => {
  currentPage.value = 1
  fetchCards()
})

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

<template>
  <BasicPage
    :title="t('agent.cards.title')"
    :description="t('agent.cards.description')"
    :breadcrumbs="[
      { title: t('nav.dashboard'), href: '/agent' },
      { title: t('nav.cards') },
    ]"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('agent.cards.generateCard') }}
      </UiButton>
    </template>

    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.cards.totalCards') }}
            </UiCardTitle>
            <Key class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ total }}
            </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('agent.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('agent.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('agent.cards.expired') }}
            </UiCardTitle>
            <Key class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ expiredCount }}
            </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('agent.cards.banned') }}
            </UiCardTitle>
            <Key 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="cards"
            :server-pagination="serverPagination"
            :search-filter="searchFilter"
            @refresh="fetchCards"
            @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('agent.cards.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="cardTypeFilter"
                :title="t('agent.cards.cardType')"
                :options="cardTypeOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('agent.cards.statusFilter')"
                :options="statusOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="startDate"
                v-model:end-model-value="endDate"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>
  </BasicPage>
</template>
