<script setup lang="ts">
import { Key, Loader2, Plus } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

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

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()

const loading = ref(true)
const cards = ref<Card[]>([])
const tableRef = ref()
const searchFilter = ref('')

const filteredCards = computed(() => {
  let result = cards.value.filter(c => c)
  if (searchFilter.value) {
    const query = searchFilter.value.toLowerCase()
    result = result.filter(c =>
      c.code?.toLowerCase().includes(query)
      || c.app_name?.toLowerCase().includes(query)
      || c.card_type_name?.toLowerCase().includes(query),
    )
  }
  return result
})

const unusedCount = computed(() => cards.value.filter(card => card.status === 'unused').length)
const usedCount = computed(() => cards.value.filter(card => card.status === 'used').length)
const expiredCount = computed(() => cards.value.filter(card => card.status === 'expired').length)
const disabledCount = computed(() => cards.value.filter(card => card.status === 'disabled').length)

async function fetchCards() {
  loading.value = true
  try {
    const data = await api.get<any>('/agent/cards')
    if (Array.isArray(data)) {
      cards.value = data
    } else if (data?.cards) {
      cards.value = data.cards
    } else if (data?.data) {
      cards.value = Array.isArray(data.data) ? data.data : []
    } else {
      cards.value = []
    }
  }
  catch (error) {
    console.error('Load cards failed:', error)
    cards.value = []
  }
  finally {
    loading.value = false
  }
}

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

function handleExport() {
  const token = localStorage.getItem('token')
  const url = `${BASE_URL}/agent/cards/export?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')
}

onMounted(() => {
  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-4">
        <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">
              {{ cards.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('agent.cards.unused') }}
            </UiCardTitle>
            <Key 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>
            <Key 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>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <div v-if="loading" class="flex items-center justify-center py-12">
            <Loader2 class="size-8 animate-spin text-muted-foreground" />
          </div>

          <DataTable
            v-else
            ref="tableRef"
            :loading
            :data="filteredCards"
            :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"
          />
        </UiCardContent>
      </UiCard>
    </div>
  </BasicPage>
</template>
