<script lang="ts" setup>
import { Icon } from '@iconify/vue'
import { toast } from 'vue-sonner'

import type { ColdWallet } from '@/services/api/monisuo-admin.api'

import { BasicPage } from '@/components/global-layout'
import {
  useGetWalletListQuery,
  useCreateWalletMutation,
  useUpdateWalletMutation,
  useDeleteWalletMutation,
  useSetDefaultWalletMutation,
  useToggleWalletStatusMutation,
} from '@/services/api/monisuo-admin.api'

const { data, isLoading, refetch } = useGetWalletListQuery()
const createMutation = useCreateWalletMutation()
const updateMutation = useUpdateWalletMutation()
const deleteMutation = useDeleteWalletMutation()
const setDefaultMutation = useSetDefaultWalletMutation()
const toggleStatusMutation = useToggleWalletStatusMutation()

const wallets = computed(() => data.value?.data || [])

const editingWallet = ref<Partial<ColdWallet>>({})
const showEditDialog = ref(false)
const isEditing = ref(false)

// 表单验证
const formErrors = ref<{ name?: string, address?: string }>({})

function validateForm(): boolean {
  formErrors.value = {}

  if (!editingWallet.value.name?.trim()) {
    formErrors.value.name = '请输入钱包名称'
    return false
  }
  if (!editingWallet.value.address?.trim()) {
    formErrors.value.address = '请输入钱包地址'
    return false
  }

  return true
}

function openCreateDialog() {
  editingWallet.value = { network: 'TRC20', status: 1, isDefault: false }
  isEditing.value = false
  formErrors.value = {}
  showEditDialog.value = true
}

function openEditDialog(wallet: ColdWallet) {
  editingWallet.value = { ...wallet }
  isEditing.value = true
  formErrors.value = {}
  showEditDialog.value = true
}

async function saveWallet() {
  if (!validateForm())
    return

  try {
    if (isEditing.value) {
      await updateMutation.mutateAsync(editingWallet.value)
      toast.success('钱包已更新')
    }
    else {
      await createMutation.mutateAsync(editingWallet.value)
      toast.success('钱包已创建')
    }
    showEditDialog.value = false
    refetch()
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || '操作失败')
  }
}

async function setDefault(wallet: ColdWallet) {
  if (wallet.isDefault)
    return

  try {
    await setDefaultMutation.mutateAsync({ id: wallet.id })
    toast.success(`已将 ${wallet.name} 设为默认`)
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || '设置失败')
  }
}

async function toggleStatus(wallet: ColdWallet) {
  try {
    await toggleStatusMutation.mutateAsync({ id: wallet.id })
    toast.success(wallet.status === 1 ? '已禁用' : '已启用')
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || '操作失败')
  }
}

async function deleteWallet(wallet: ColdWallet) {
  if (!confirm(`确定删除钱包 ${wallet.name} 吗?`))
    return

  try {
    await deleteMutation.mutateAsync({ id: wallet.id })
    toast.success('钱包已删除')
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || '删除失败')
  }
}
</script>

<template>
  <BasicPage title="冷钱包管理" description="配置充值收款地址">
    <template #actions>
      <UiButton @click="openCreateDialog">
        <Icon icon="lucide:plus" class="mr-2 h-4 w-4" />
        新增钱包
      </UiButton>
    </template>

    <!-- PC端表格 -->
    <UiCard class="hidden md:block overflow-x-auto p-4">
      <UiTable v-if="!isLoading">
        <UiTableHeader>
          <UiTableRow>
            <UiTableHead>名称</UiTableHead>
            <UiTableHead>地址</UiTableHead>
            <UiTableHead>网络</UiTableHead>
            <UiTableHead>默认</UiTableHead>
            <UiTableHead>状态</UiTableHead>
            <UiTableHead>操作</UiTableHead>
          </UiTableRow>
        </UiTableHeader>
        <UiTableBody>
          <UiTableRow v-for="wallet in wallets" :key="wallet.id">
            <UiTableCell class="font-medium">{{ wallet.name }}</UiTableCell>
            <UiTableCell class="font-mono text-xs max-w-[200px] truncate">
              {{ wallet.address }}
            </UiTableCell>
            <UiTableCell>{{ wallet.network }}</UiTableCell>
            <UiTableCell>
              <UiBadge v-if="wallet.isDefault" variant="default">
                默认
              </UiBadge>
              <span v-else class="text-muted-foreground">-</span>
            </UiTableCell>
            <UiTableCell>
              <UiBadge :variant="wallet.status === 1 ? 'default' : 'destructive'">
                {{ wallet.status === 1 ? '启用' : '禁用' }}
              </UiBadge>
            </UiTableCell>
            <UiTableCell>
              <div class="flex gap-2">
                <UiButton size="sm" variant="ghost" @click="openEditDialog(wallet)">
                  编辑
                </UiButton>
                <UiButton
                  size="sm"
                  variant="ghost"
                  :disabled="wallet.isDefault"
                  @click="setDefault(wallet)"
                >
                  设为默认
                </UiButton>
                <UiButton
                  size="sm"
                  variant="ghost"
                  @click="toggleStatus(wallet)"
                >
                  {{ wallet.status === 1 ? '禁用' : '启用' }}
                </UiButton>
                <UiButton
                  size="sm"
                  variant="destructive"
                  @click="deleteWallet(wallet)"
                >
                  删除
                </UiButton>
              </div>
            </UiTableCell>
          </UiTableRow>
          <UiTableRow v-if="wallets.length === 0">
            <UiTableCell colspan="6" class="text-center text-muted-foreground py-8">
              暂无钱包数据
            </UiTableCell>
          </UiTableRow>
        </UiTableBody>
      </UiTable>
      <div v-else class="flex justify-center py-8">
        <Icon icon="lucide:loader-2" class="h-6 w-6 animate-spin" />
      </div>
    </UiCard>

    <!-- 移动端卡片 -->
    <div class="md:hidden space-y-4">
      <div v-if="isLoading" class="flex justify-center py-8">
        <Icon icon="lucide:loader-2" class="h-6 w-6 animate-spin" />
      </div>
      <template v-else-if="wallets.length > 0">
        <UiCard v-for="wallet in wallets" :key="wallet.id" class="p-4">
          <div class="flex justify-between items-start mb-2">
            <div>
              <div class="font-medium">{{ wallet.name }}</div>
              <div class="text-xs text-muted-foreground">{{ wallet.network }}</div>
            </div>
            <div class="flex gap-1">
              <UiBadge v-if="wallet.isDefault" variant="default" class="text-xs">
                默认
              </UiBadge>
              <UiBadge :variant="wallet.status === 1 ? 'default' : 'destructive'" class="text-xs">
                {{ wallet.status === 1 ? '启用' : '禁用' }}
              </UiBadge>
            </div>
          </div>
          <div class="font-mono text-xs break-all mb-3 text-muted-foreground">
            {{ wallet.address }}
          </div>
          <div class="flex flex-wrap gap-2">
            <UiButton size="sm" variant="outline" @click="openEditDialog(wallet)">
              编辑
            </UiButton>
            <UiButton
              size="sm"
              variant="outline"
              :disabled="wallet.isDefault"
              @click="setDefault(wallet)"
            >
              设为默认
            </UiButton>
            <UiButton
              size="sm"
              variant="outline"
              @click="toggleStatus(wallet)"
            >
              {{ wallet.status === 1 ? '禁用' : '启用' }}
            </UiButton>
            <UiButton
              size="sm"
              variant="destructive"
              @click="deleteWallet(wallet)"
            >
              删除
            </UiButton>
          </div>
        </UiCard>
      </template>
      <div v-else class="text-center text-muted-foreground py-8">
        暂无钱包数据
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <UiDialog v-model:open="showEditDialog">
      <UiDialogContent>
        <UiDialogHeader>
          <UiDialogTitle>{{ isEditing ? '编辑钱包' : '新增钱包' }}</UiDialogTitle>
        </UiDialogHeader>
        <div class="grid gap-4 py-4">
          <div class="grid gap-2">
            <UiLabel>钱包名称 <span class="text-red-500">*</span></UiLabel>
            <UiInput v-model="editingWallet.name" placeholder="如：主钱包" />
            <span v-if="formErrors.name" class="text-xs text-red-500">{{ formErrors.name }}</span>
          </div>
          <div class="grid gap-2">
            <UiLabel>钱包地址 <span class="text-red-500">*</span></UiLabel>
            <UiInput v-model="editingWallet.address" placeholder="TRC20/ERC20 地址" />
            <span v-if="formErrors.address" class="text-xs text-red-500">{{ formErrors.address }}</span>
          </div>
          <div class="grid gap-2">
            <UiLabel>网络类型</UiLabel>
            <UiSelect v-model="editingWallet.network">
              <UiSelectTrigger>
                <UiSelectValue placeholder="选择网络" />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="TRC20">
                  TRC20 (波场)
                </UiSelectItem>
                <UiSelectItem value="ERC20">
                  ERC20 (以太坊)
                </UiSelectItem>
                <UiSelectItem value="BEP20">
                  BEP20 (币安智能链)
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
          </div>
          <div class="flex items-center gap-2">
            <UiCheckbox
              :checked="editingWallet.isDefault"
              @update:checked="editingWallet.isDefault = $event"
            />
            <UiLabel class="cursor-pointer" @click="editingWallet.isDefault = !editingWallet.isDefault">
              设为默认钱包
            </UiLabel>
          </div>
        </div>
        <UiDialogFooter>
          <UiButton variant="outline" @click="showEditDialog = false">
            取消
          </UiButton>
          <UiButton
            :disabled="createMutation.isPending.value || updateMutation.isPending.value"
            @click="saveWallet"
          >
            {{ isEditing ? '保存' : '创建' }}
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
