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

import type { PaymentChannel } from '@/pages/admin/payment-channels/data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/payment-channels/components/data-table.vue'
import api from '@/services/api'

const router = useRouter()

const loading = ref(true)
const paymentChannels = ref<PaymentChannel[]>([])
const tableRef = ref()

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

const activeCount = computed(() => paymentChannels.value.filter(c => c.status === 'active').length)
const inactiveCount = computed(() => paymentChannels.value.filter(c => c.status === 'inactive').length)

async function fetchPaymentChannels() {
  loading.value = true
  try {
    const data = await api.get<{ payment_channels: PaymentChannel[] }>('/dev/system-settings/payment')
    paymentChannels.value = data?.payment_channels || []
  }
  catch (error) {
    console.error('加载支付渠道失败:', error)
    paymentChannels.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/payment-channels/create')
}

function goToEdit(channel: PaymentChannel) {
  router.push(`/admin/payment-channels/${channel.id}`)
}

async function toggleStatus(channel: PaymentChannel) {
  const newStatus = channel.status === 'active' ? 'inactive' : 'active'
  try {
    await api.put(`/dev/payment-channels/${channel.id}/status`, { status: newStatus })
    toast.success('状态更新成功')
    fetchPaymentChannels()
  }
  catch (error: any) {
    console.error('更新状态失败:', error)
    toast.error(error.message || '更新失败')
  }
}

function confirmDelete(channel: PaymentChannel) {
  deleteTarget.value = channel
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/payment-channels/${deleteTarget.value.id}`)
    toast.success('删除成功')
    fetchPaymentChannels()
  }
  catch (error: any) {
    console.error('删除支付渠道失败:', error)
    toast.error(error.message || '删除失败')
  }
  finally {
    deleteTarget.value = null
  }
}

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

async function handleBatchDelete() {
  try {
    await api.delete('/dev/payment-channels/batch', { ids: batchDeleteIds.value } as any)
    toast.success('批量删除成功')
    fetchPaymentChannels()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || '批量删除失败')
  }
  finally {
    batchDeleteIds.value = []
  }
}

async function batchToggleStatus(ids: number[], status: string) {
  try {
    await api.put('/dev/payment-channels/batch/status', { ids, status })
    toast.success('批量更新成功')
    fetchPaymentChannels()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || '批量更新失败')
  }
}

onMounted(() => {
  fetchPaymentChannels()
})
</script>

<template>
  <BasicPage
    title="支付渠道"
    description="管理系统的支付渠道配置"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        添加渠道
      </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">
              总渠道数
            </UiCardTitle>
            <CreditCard class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ paymentChannels.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">
              已启用
            </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">
              已禁用
            </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">
              启用率
            </UiCardTitle>
            <Percent class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ paymentChannels.length ? Math.round(activeCount / paymentChannels.length * 100) : 0 }}%
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="paymentChannels"
            :on-toggle-status="toggleStatus"
            :on-edit="goToEdit"
            :on-delete="confirmDelete"
            @refresh="fetchPaymentChannels"
            @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) || [])"
          />
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleDelete"
    >
      <template #title>
        删除支付渠道
      </template>
      <template #description>
        确定要删除支付渠道"{{ deleteTarget?.name }}"吗？此操作不可撤销。
      </template>
    </ConfirmDialog>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleBatchDelete"
    >
      <template #title>
        批量删除支付渠道
      </template>
      <template #description>
        确定要删除选中的 {{ batchDeleteIds.length }} 个支付渠道吗？此操作不可撤销。
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
