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

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

import { BasicPage } from '@/components/global-layout'
import { useGetCoinListQuery, useSaveCoinMutation, useUpdateCoinPriceMutation, useUpdateCoinStatusMutation } from '@/services/api/monisuo-admin.api'

const { data, isLoading, refetch } = useGetCoinListQuery()
const saveMutation = useSaveCoinMutation()
const priceMutation = useUpdateCoinPriceMutation()
const statusMutation = useUpdateCoinStatusMutation()

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

const editingCoin = ref<Partial<Coin>>({})
const showEditDialog = ref(false)
const showPriceDialog = ref(false)
const priceInput = ref<number>(0)
const editingCode = ref('')

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

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

  if (!editingCoin.value.code?.trim()) {
    formErrors.value.code = '请输入币种代码'
    return false
  }
  if (!editingCoin.value.name?.trim()) {
    formErrors.value.name = '请输入币种名称'
    return false
  }

  return true
}

function openEditDialog(coin?: Coin) {
  if (coin) {
    editingCoin.value = { ...coin }
  }
  else {
    editingCoin.value = { priceType: 2, status: 1, price: 0 }
  }
  formErrors.value = {}
  showEditDialog.value = true
}

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

  try {
    await saveMutation.mutateAsync(editingCoin.value as Coin)
    toast.success(editingCoin.value.id ? '币种已更新' : '币种已添加')
    showEditDialog.value = false
    refetch()
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || '操作失败')
  }
}

function openPriceDialog(coin: Coin) {
  editingCode.value = coin.code
  priceInput.value = coin.price
  showPriceDialog.value = true
}

async function updatePrice() {
  if (priceInput.value <= 0) {
    toast.error('请输入有效价格')
    return
  }

  try {
    await priceMutation.mutateAsync({ code: editingCode.value, price: priceInput.value })
    toast.success('价格已更新')
    showPriceDialog.value = false
    refetch()
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || '操作失败')
  }
}

async function toggleStatus(coin: Coin) {
  const newStatus = coin.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '上架' : '下架'

  try {
    await statusMutation.mutateAsync({ coinId: coin.id, status: newStatus })
    toast.success(`已${action} ${coin.code}`)
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || `${action}失败`)
  }
}

function formatPrice(price: number): string {
  if (!price)
    return '0.00'
  return price >= 1 ? price.toLocaleString(undefined, { maximumFractionDigits: 2 }) : price.toFixed(6)
}
</script>

<template>
  <BasicPage title="币种管理" description="管理交易币种">
    <div class="space-y-4">
      <div class="flex justify-end">
        <UiButton @click="openEditDialog()">
          <Icon icon="lucide:plus" class="size-4 mr-2" />
          新增币种
        </UiButton>
      </div>

      <!-- PC端表格 -->
      <UiCard class="hidden md:block overflow-x-auto p-4"">
        <UiTable>
          <UiTableHeader>
            <UiTableRow>
              <UiTableHead class="w-[80px]">
                ID
              </UiTableHead>
              <UiTableHead>代码</UiTableHead>
              <UiTableHead>名称</UiTableHead>
              <UiTableHead class="text-right">
                价格
              </UiTableHead>
              <UiTableHead>价格类型</UiTableHead>
              <UiTableHead>状态</UiTableHead>
              <UiTableHead class="text-right">
                操作
              </UiTableHead>
            </UiTableRow>
          </UiTableHeader>
          <UiTableBody>
            <UiTableRow v-if="isLoading">
              <UiTableCell :col-span="7" class="text-center py-8">
                <UiSpinner class="mx-auto" />
              </UiTableCell>
            </UiTableRow>
            <UiTableRow v-else-if="coins.length === 0">
              <UiTableCell :col-span="7" class="text-center py-8 text-muted-foreground">
                暂无数据
              </UiTableCell>
            </UiTableRow>
            <UiTableRow v-for="coin in coins" :key="coin.id">
              <UiTableCell>{{ coin.id }}</UiTableCell>
              <UiTableCell class="font-mono font-medium">
                {{ coin.code }}
              </UiTableCell>
              <UiTableCell>{{ coin.name }}</UiTableCell>
              <UiTableCell class="text-right font-mono">
                ${{ formatPrice(coin.price) }}
              </UiTableCell>
              <UiTableCell>
                <UiBadge variant="outline">
                  <Icon v-if="coin.priceType === 1" icon="lucide:zap" class="size-3 mr-1" />
                  {{ coin.priceType === 1 ? '实时' : '手动' }}
                </UiBadge>
              </UiTableCell>
              <UiTableCell>
                <UiBadge :variant="coin.status === 1 ? 'default' : 'secondary'">
                  {{ coin.status === 1 ? '上架' : '下架' }}
                </UiBadge>
              </UiTableCell>
              <UiTableCell class="text-right">
                <div class="flex justify-end gap-1">
                  <UiButton size="sm" variant="ghost" @click="openEditDialog(coin)">
                    <Icon icon="lucide:pencil" class="size-4" />
                  </UiButton>
                  <UiButton
                    size="sm"
                    variant="ghost"
                    :disabled="coin.priceType === 1"
                    :title="coin.priceType === 1 ? '实时价格不支持手动调整' : '调整价格'"
                    @click="openPriceDialog(coin)"
                  >
                    <Icon icon="lucide:dollar-sign" class="size-4" />
                  </UiButton>
                  <UiButton
                    size="sm"
                    variant="ghost"
                    :disabled="statusMutation.isPending.value"
                    @click="toggleStatus(coin)"
                  >
                    <Icon :icon="coin.status === 1 ? 'lucide:arrow-down' : 'lucide:arrow-up'" class="size-4" />
                  </UiButton>
                </div>
              </UiTableCell>
            </UiTableRow>
          </UiTableBody>
        </UiTable>
      </UiCard>

      <!-- 移动端卡片列表 -->
      <div class="md:hidden space-y-3">
        <div v-if="isLoading" class="text-center py-8">
          <UiSpinner class="mx-auto" />
        </div>
        <template v-else-if="coins.length > 0">
          <UiCard v-for="coin in coins" :key="coin.id" class="p-4">
            <div class="flex items-start justify-between">
              <div class="space-y-1">
                <div class="flex items-center gap-2">
                  <span class="font-mono font-bold">{{ coin.code }}</span>
                  <UiBadge variant="outline" class="text-xs">
                    {{ coin.priceType === 1 ? '实时' : '手动' }}
                  </UiBadge>
                </div>
                <div class="text-sm text-muted-foreground">
                  {{ coin.name }}
                </div>
              </div>
              <UiBadge :variant="coin.status === 1 ? 'default' : 'secondary'">
                {{ coin.status === 1 ? '上架' : '下架' }}
              </UiBadge>
            </div>
            <div class="mt-3 pt-3 border-t">
              <div class="text-xl font-mono font-bold text-green-600 dark:text-green-400">
                ${{ formatPrice(coin.price) }}
              </div>
            </div>
            <div class="mt-3 flex gap-2">
              <UiButton size="sm" variant="outline" class="flex-1" @click="openEditDialog(coin)">
                编辑
              </UiButton>
              <UiButton
                size="sm"
                variant="outline"
                class="flex-1"
                :disabled="coin.priceType === 1"
                @click="openPriceDialog(coin)"
              >
                调价
              </UiButton>
              <UiButton
                size="sm"
                variant="outline"
                class="flex-1"
                :disabled="statusMutation.isPending.value"
                @click="toggleStatus(coin)"
              >
                {{ coin.status === 1 ? '下架' : '上架' }}
              </UiButton>
            </div>
          </UiCard>
        </template>
        <div v-else class="text-center py-8 text-muted-foreground">
          暂无数据
        </div>
      </div>
    </div>

    <!-- 编辑币种弹窗 -->
    <UiDialog v-model:open="showEditDialog">
      <UiDialogContent class="max-w-md">
        <UiDialogHeader>
          <UiDialogTitle>{{ editingCoin.id ? '编辑币种' : '新增币种' }}</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="editingCoin.code"
              placeholder="BTC"
              :class="{ 'border-red-500': formErrors.code }"
              @input="formErrors.code = undefined"
            />
            <p v-if="formErrors.code" class="text-sm text-red-500">
              {{ formErrors.code }}
            </p>
          </div>
          <div class="grid gap-2">
            <UiLabel>名称 <span class="text-red-500">*</span></UiLabel>
            <UiInput
              v-model="editingCoin.name"
              placeholder="比特币"
              :class="{ 'border-red-500': formErrors.name }"
              @input="formErrors.name = undefined"
            />
            <p v-if="formErrors.name" class="text-sm text-red-500">
              {{ formErrors.name }}
            </p>
          </div>
          <div class="grid gap-2">
            <UiLabel>价格类型</UiLabel>
            <UiSelect v-model="editingCoin.priceType">
              <UiSelectTrigger>
                <UiSelectValue />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem :value="1">
                  实时（从市场获取）
                </UiSelectItem>
                <UiSelectItem :value="2">
                  手动（自定义价格）
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
          </div>
          <div v-if="editingCoin.priceType === 2" class="grid gap-2">
            <UiLabel>初始价格 ($)</UiLabel>
            <UiInput v-model.number="editingCoin.price" type="number" step="0.000001" placeholder="0.00" />
          </div>
        </div>
        <UiDialogFooter>
          <UiButton variant="outline" @click="showEditDialog = false">
            取消
          </UiButton>
          <UiButton :disabled="saveMutation.isPending.value" @click="saveCoin">
            <UiSpinner v-if="saveMutation.isPending.value" class="mr-2" />
            保存
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>

    <!-- 调价弹窗 -->
    <UiDialog v-model:open="showPriceDialog">
      <UiDialogContent class="max-w-sm">
        <UiDialogHeader>
          <UiDialogTitle>调整价格 - {{ editingCode }}</UiDialogTitle>
        </UiDialogHeader>
        <div class="grid gap-4 py-4">
          <div class="grid gap-2">
            <UiLabel>新价格 ($)</UiLabel>
            <UiInput
              v-model.number="priceInput"
              type="number"
              step="0.000001"
              placeholder="0.00"
              autofocus
            />
          </div>
        </div>
        <UiDialogFooter>
          <UiButton variant="outline" @click="showPriceDialog = false">
            取消
          </UiButton>
          <UiButton :disabled="priceMutation.isPending.value" @click="updatePrice">
            <UiSpinner v-if="priceMutation.isPending.value" class="mr-2" />
            确认
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
