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

import type { CardType } from '@/pages/admin/card-types/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/card-types/components/data-table.vue'

const { t } = useI18n()

const router = useRouter()
const API_BASE = 'http://localhost:8080/api/v1'

interface Application {
  id: string
  name: string
}

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

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

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

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

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

const filteredCardTypes = computed(() => {
  let result = cardTypes.value

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

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

  return result
})

const activeTypesCount = computed(() => filteredCardTypes.value.filter(type => type.status === 'active').length)
const totalGeneratedCount = computed(() => filteredCardTypes.value.reduce((sum, type) => sum + (type.generatedCount || 0), 0))
const totalValue = computed(() => filteredCardTypes.value.reduce((sum, type) => sum + (type.price * (type.generatedCount || 0)), 0))

async function fetchCardTypes() {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/card-types`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      cardTypes.value = Array.isArray(data.data?.card_types) ? data.data.card_types : []
    }
    else {
      cardTypes.value = []
    }
  }
  catch (error) {
    console.error('获取卡密类型失败:', error)
    cardTypes.value = []
  }
  finally {
    loading.value = false
  }
}

async function fetchApplications() {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/applications`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      applications.value = Array.isArray(data.data?.applications) ? data.data.applications : []
    }
    else {
      applications.value = []
    }
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
    applications.value = []
  }
}

function goToCreate() {
  router.push('/admin/card-types/create')
}

function goToEdit(type: CardType) {
  router.push(`/admin/card-types/${type.id}`)
}

async function toggleStatus(type: CardType) {
  try {
    const token = localStorage.getItem('token')
    const newStatus = type.status === 'active' ? 'inactive' : 'active'
    const response = await fetch(`${API_BASE}/dev/card-types/${type.id}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ status: newStatus }),
    })

    const data = await response.json()
    if (data.code === 200) {
      toast.success(t('admin.cardTypes.statusUpdateSuccess'))
      fetchCardTypes()
    }
    else {
      toast.error(data.message || t('admin.cardTypes.statusUpdateFailed'))
    }
  }
  catch (error) {
    console.error('切换卡密类型状态失败:', error)
    toast.error(t('admin.cardTypes.statusUpdateFailed'))
  }
}

function confirmDeleteType(type: CardType) {
  deleteTarget.value = type
  deleteDialogOpen.value = true
}

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

  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/card-types/${deleteTarget.value.id}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })

    const data = await response.json()
    if (data.code === 200) {
      toast.success(t('admin.cardTypes.deleteSuccess'))
      fetchCardTypes()
    }
    else {
      toast.error(data.message || t('admin.cardTypes.deleteFailed'))
    }
  }
  catch (error) {
    console.error('删除卡密类型失败:', error)
    toast.error(t('admin.cardTypes.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

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

async function handleBatchDelete() {
  try {
    const token = localStorage.getItem('token')
    let successCount = 0
    let failCount = 0

    for (const id of batchDeleteIds.value) {
      const response = await fetch(`${API_BASE}/dev/card-types/${id}`, {
        method: 'DELETE',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      const data = await response.json()
      if (data.code === 200) {
        successCount++
      }
      else {
        failCount++
      }
    }

    if (successCount > 0) {
      toast.success(t('admin.cardTypes.deleteSuccess'))
      fetchCardTypes()
    }
    if (failCount > 0) {
      toast.error(t('admin.cardTypes.deleteFailed'))
    }
  }
  catch (error) {
    console.error('批量删除失败:', error)
    toast.error(t('admin.cardTypes.deleteFailed'))
  }
  finally {
    batchDeleteIds.value = []
  }
}

async function batchToggleStatus(ids: (string | number)[], status: string) {
  try {
    const token = localStorage.getItem('token')
    let successCount = 0
    let failCount = 0

    for (const id of ids) {
      const response = await fetch(`${API_BASE}/dev/card-types/${id}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ status }),
      })
      const data = await response.json()
      if (data.code === 200) {
        successCount++
      }
      else {
        failCount++
      }
    }

    if (successCount > 0) {
      toast.success(t('admin.cardTypes.batchUpdateSuccess'))
      fetchCardTypes()
    }
    if (failCount > 0) {
      toast.error(t('admin.cardTypes.batchUpdateFailed'))
    }
  }
  catch (error) {
    console.error('批量更新状态失败:', error)
    toast.error(t('admin.cardTypes.batchUpdateFailed'))
  }
}

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

<template>
  <BasicPage
    :title="t('admin.cardTypes.title')"
    :description="t('admin.cardTypes.description')"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.cardTypes.createCardType') }}
      </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.cardTypes.totalTypes') }}
            </UiCardTitle>
            <Layers class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredCardTypes.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.cardTypes.activeTypes') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeTypesCount }}
            </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.cardTypes.generatedCards') }}
            </UiCardTitle>
            <Hash class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalGeneratedCount }}
            </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.cardTypes.totalValue') }}
            </UiCardTitle>
            <DollarSign class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              ¥{{ totalValue }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredCardTypes"
            :on-edit="goToEdit"
            :on-toggle-status="toggleStatus"
            :on-delete="confirmDeleteType"
            @refresh="fetchCardTypes"
            @batch-enable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'inactive').map((r: any) => r.original.id) || [], 'active')"
            @batch-disable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'active').map((r: any) => r.original.id) || [], 'inactive')"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.cardTypes.columns.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.cardTypes.columns.status')"
                :options="statusOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

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

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