<script setup lang="ts">
import { Check, CheckCircle, Clock, Send, Share2, Trash2, UserPlus, Wallet, X } 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 { AgentApp, AgentRequest, CombinedItem } from '@/pages/admin/agent-apps/data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import BulkActions from '@/components/data-table/bulk-actions.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/agent-apps/components/data-table.vue'
import api from '@/services/api'

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

const loading = ref(true)
const agentApps = ref<AgentApp[]>([])
const requests = ref<AgentRequest[]>([])
const myRequests = ref<AgentRequest[]>([])
const tableRef = ref()
const showRejectDialog = ref(false)
const showRemoveDialog = ref(false)
const showBatchRejectDialog = ref(false)
const showBatchRemoveDialog = ref(false)
const rejectingItem = ref<CombinedItem | null>(null)
const removingItem = ref<CombinedItem | null>(null)
const batchRejectIds = ref<(string | number)[]>([])
const batchRemoveIds = ref<(string | number)[]>([])

const activeCount = computed(() => agentApps.value.filter(app => app.status === 'active').length)
const pendingCount = computed(() => requests.value.filter(r => r.status === 'pending').length + myRequests.value.filter(r => r.status === 'pending').length)
const totalBalance = computed(() => agentApps.value.reduce((sum, app) => sum + app.balance, 0))

const allItems = computed<CombinedItem[]>(() => {
  const items = agentApps.value.map(item => ({
    ...item,
    itemType: 'authorization' as const,
    status: item.status,
    created_at: item.created_at,
    hasAuthorization: item.status === 'active' || item.status === 'inactive',
    authorizationId: item.id,
  }))

  const requestItems = requests.value
    .filter(item => item.status === 'pending')
    .map(item => ({
      id: item.id,
      agent_id: item.agent_id,
      agent_name: item.agent_name,
      application_id: item.application_id,
      app_name: item.app_name,
      status: item.status,
      discount: 1,
      balance: 0,
      card_types: [],
      created_at: item.created_at,
      itemType: 'request' as const,
      hasAuthorization: false,
      authorizationId: null,
    }))

  const myRequestItems = myRequests.value
    .filter(item => item.status === 'pending')
    .map(item => ({
      id: item.id,
      agent_id: item.admin_id,
      agent_name: item.admin_name,
      application_id: item.application_id,
      app_name: item.app_name,
      status: item.status,
      discount: 1,
      balance: 0,
      card_types: [],
      created_at: item.created_at,
      itemType: 'my_request' as const,
      hasAuthorization: false,
      authorizationId: null,
    }))

  return [...items, ...requestItems, ...myRequestItems].sort((a, b) => {
    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
  })
})

async function fetchData() {
  loading.value = true
  try {
    const [appsData, requestsData, myRequestsData] = await Promise.all([
      api.get<{ agent_apps: AgentApp[] }>('/dev/agent-apps'),
      api.get<{ requests: AgentRequest[] }>('/dev/agent-apps/requests'),
      api.get<{ requests: AgentRequest[] }>('/dev/agent-apps/my-requests'),
    ])

    agentApps.value = appsData?.agent_apps || []
    requests.value = requestsData?.requests || []
    myRequests.value = myRequestsData?.requests || []
  }
  catch (error) {
    console.error('获取数据失败:', error)
    toast.error(t('common.fetchFailed'))
  }
  finally {
    loading.value = false
  }
}

function goToRequest() {
  router.push('/admin/agent-apps/request')
}

function goToInvite() {
  router.push('/admin/agent-apps/invite')
}

async function approveRequest(item: CombinedItem) {
  try {
    await api.post(`/dev/agent-apps/requests/${item.id}/approve`)
    toast.success(t('admin.agentApps.approveSuccess'))
    fetchData()
  }
  catch (error: any) {
    console.error('批准申请失败:', error)
    toast.error(error.message || t('admin.agentApps.approveFailed'))
  }
}

async function rejectRequest() {
  if (!rejectingItem.value)
    return

  try {
    await api.post(`/dev/agent-apps/requests/${rejectingItem.value.id}/reject`, { reason: '' })
    toast.success(t('admin.agentApps.rejectSuccess'))
    showRejectDialog.value = false
    fetchData()
  }
  catch (error: any) {
    console.error('拒绝申请失败:', error)
    toast.error(error.message || t('admin.agentApps.rejectFailed'))
  }
}

function confirmReject(item: CombinedItem) {
  rejectingItem.value = item
  showRejectDialog.value = true
}

async function removeItem() {
  if (!removingItem.value)
    return

  try {
    const endpoint = removingItem.value.itemType === 'my_request'
      ? `/dev/agent-apps/my-requests/${removingItem.value.id}`
      : `/dev/agent-apps/${removingItem.value.authorizationId}`

    await api.delete(endpoint)
    toast.success(t('common.success'))
    showRemoveDialog.value = false
    fetchData()
  }
  catch (error: any) {
    console.error('操作失败:', error)
    toast.error(error.message || t('common.failed'))
  }
}

function confirmRemove(item: CombinedItem) {
  removingItem.value = item
  showRemoveDialog.value = true
}

async function batchApprove(ids: (string | number)[]) {
  try {
    await api.post('/dev/agent-apps/requests/batch-approve', { ids })
    toast.success(t('admin.agentApps.batchApproveSuccess'))
    fetchData()
  }
  catch (error: any) {
    console.error('批量批准失败:', error)
    toast.error(error.message || t('admin.agentApps.batchApproveFailed'))
  }
}

async function batchReject() {
  if (batchRejectIds.value.length === 0)
    return

  try {
    await api.post('/dev/agent-apps/requests/batch-reject', { ids: batchRejectIds.value, reason: '' })
    toast.success(t('admin.agentApps.batchRejectSuccess'))
    showBatchRejectDialog.value = false
    fetchData()
  }
  catch (error: any) {
    console.error('批量拒绝失败:', error)
    toast.error(error.message || t('admin.agentApps.batchRejectFailed'))
  }
}

function confirmBatchReject(ids: (string | number)[]) {
  batchRejectIds.value = ids
  showBatchRejectDialog.value = true
}

async function batchRemove() {
  if (batchRemoveIds.value.length === 0)
    return

  try {
    await api.delete('/dev/agent-apps/batch', { ids: batchRemoveIds.value })
    toast.success(t('admin.agentApps.batchRemoveSuccess'))
    showBatchRemoveDialog.value = false
    fetchData()
  }
  catch (error: any) {
    console.error('批量移除失败:', error)
    toast.error(error.message || t('admin.agentApps.batchRemoveFailed'))
  }
}

function confirmBatchRemove(ids: (string | number)[]) {
  batchRemoveIds.value = ids
  showBatchRemoveDialog.value = true
}

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

<template>
  <BasicPage
    :title="t('admin.agentApps.title')"
    :description="t('admin.agentApps.description')"
    sticky
  >
    <template #actions>
      <UiButton variant="outline" @click="goToRequest">
        <Send class="mr-2 h-4 w-4" />
        {{ t('admin.agentApps.requestAuth') }}
      </UiButton>
      <UiButton @click="goToInvite">
        <UserPlus class="mr-2 h-4 w-4" />
        {{ t('admin.agentApps.inviteAuth') }}
      </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.agentApps.totalAuth') }}
            </UiCardTitle>
            <Share2 class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ agentApps.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.agentApps.activeAuth') }}
            </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">
              {{ t('admin.agentApps.pendingRequests') }}
            </UiCardTitle>
            <Clock class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ pendingCount }}
            </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.agentApps.agentBalance') }}
            </UiCardTitle>
            <Wallet class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              ¥{{ totalBalance.toFixed(2) }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="allItems"
            :on-approve="approveRequest"
            :on-reject="confirmReject"
            :on-remove="confirmRemove"
            @refresh="fetchData"
          />
        </UiCardContent>
      </UiCard>
    </div>

    <BulkActions
      v-if="tableRef?.table"
      :table="tableRef.table"
      :entity-name="t('admin.agentApps.auth')"
    >
      <UiButton
        variant="outline"
        size="sm"
        @click="batchApprove(tableRef.table.getSelectedRowModel().rows.map((r: any) => r.original.id))"
      >
        <Check class="mr-2 h-4 w-4" />
        {{ t('admin.agentApps.batchApprove') }}
      </UiButton>
      <UiButton
        variant="outline"
        size="sm"
        @click="confirmBatchReject(tableRef.table.getSelectedRowModel().rows.map((r: any) => r.original.id))"
      >
        <X class="mr-2 h-4 w-4" />
        {{ t('admin.agentApps.batchReject') }}
      </UiButton>
      <UiButton
        variant="destructive"
        size="sm"
        @click="confirmBatchRemove(tableRef.table.getSelectedRowModel().rows.map((r: any) => r.original.id))"
      >
        <Trash2 class="mr-2 h-4 w-4" />
        {{ t('admin.agentApps.batchRemove') }}
      </UiButton>
    </BulkActions>

    <ConfirmDialog
      v-model:open="showRejectDialog"
      :title="t('admin.agentApps.reject')"
      :description="t('admin.agentApps.rejectConfirm')"
      confirm-text="确定"
      @confirm="rejectRequest"
    />

    <ConfirmDialog
      v-model:open="showRemoveDialog"
      :title="t('admin.agentApps.remove')"
      :description="removingItem?.itemType === 'my_request' ? t('admin.agentApps.withdrawConfirm') : t('admin.agentApps.removeConfirm')"
      confirm-text="确定"
      @confirm="removeItem"
    />

    <ConfirmDialog
      v-model:open="showBatchRejectDialog"
      :title="t('admin.agentApps.batchReject')"
      :description="t('admin.agentApps.batchRejectConfirm', { count: batchRejectIds.length })"
      confirm-text="确定"
      @confirm="batchReject"
    />

    <ConfirmDialog
      v-model:open="showBatchRemoveDialog"
      :title="t('admin.agentApps.batchRemove')"
      :description="t('admin.agentApps.batchRemoveConfirm', { count: batchRemoveIds.length })"
      confirm-text="确定"
      @confirm="batchRemove"
    />
  </BasicPage>
</template>
