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

import type { EmailConfig } from '@/pages/admin/email-settings/data/schema'

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

const router = useRouter()

const loading = ref(true)
const emailConfigs = ref<EmailConfig[]>([])
const tableRef = ref()

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

const testDialogOpen = ref(false)
const testTarget = ref<EmailConfig | null>(null)
const testEmail = ref('')
const testSending = ref(false)

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

async function fetchEmailConfigs() {
  loading.value = true
  try {
    const data = await api.get<{ email_configs: EmailConfig[] }>('/dev/email-configs')
    emailConfigs.value = data?.email_configs || []
  }
  catch (error) {
    console.error('加载邮箱配置失败:', error)
    emailConfigs.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/email-settings/create')
}

function goToEdit(config: EmailConfig) {
  router.push(`/admin/email-settings/${config.id}`)
}

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

function confirmDelete(config: EmailConfig) {
  deleteTarget.value = config
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/email-configs/${deleteTarget.value.id}`)
    toast.success('删除成功')
    fetchEmailConfigs()
  }
  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/email-configs/batch', { ids: batchDeleteIds.value } as any)
    toast.success('批量删除成功')
    fetchEmailConfigs()
  }
  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/email-configs/batch/status', { ids, status })
    toast.success('批量更新成功')
    fetchEmailConfigs()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || '批量更新失败')
  }
}

function openTestDialog(config: EmailConfig) {
  testTarget.value = config
  testEmail.value = ''
  testDialogOpen.value = true
}

async function handleTest() {
  if (!testTarget.value || !testEmail.value)
    return

  testSending.value = true
  try {
    await api.post(`/dev/email-configs/${testTarget.value.id}/test`, { email: testEmail.value })
    toast.success('测试邮件已发送')
    testDialogOpen.value = false
  }
  catch (error: any) {
    console.error('发送测试邮件失败:', error)
    toast.error(error.message || '发送失败')
  }
  finally {
    testSending.value = false
  }
}

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

<template>
  <BasicPage
    title="邮箱配置"
    description="管理系统的SMTP邮箱服务配置"
    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>
            <Mail class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ emailConfigs.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">
              {{ emailConfigs.length ? Math.round(activeCount / emailConfigs.length * 100) : 0 }}%
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="emailConfigs"
            :on-toggle-status="toggleStatus"
            :on-edit="goToEdit"
            :on-delete="confirmDelete"
            :on-test="openTestDialog"
            @refresh="fetchEmailConfigs"
            @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>

    <UiDialog v-model:open="testDialogOpen">
      <UiDialogContent class="sm:max-w-md">
        <UiDialogHeader>
          <UiDialogTitle>发送测试邮件</UiDialogTitle>
          <UiDialogDescription>
            将使用"{{ testTarget?.name }}"配置发送测试邮件
          </UiDialogDescription>
        </UiDialogHeader>
        <div class="space-y-4 py-4">
          <div class="space-y-2">
            <UiLabel for="test-email">收件人邮箱</UiLabel>
            <UiInput
              id="test-email"
              v-model="testEmail"
              type="email"
              placeholder="请输入收件人邮箱地址"
              :disabled="testSending"
            />
          </div>
        </div>
        <UiDialogFooter>
          <UiButton variant="outline" @click="testDialogOpen = false">
            取消
          </UiButton>
          <UiButton :disabled="!testEmail || testSending" @click="handleTest">
            <Loader2 v-if="testSending" class="mr-2 h-4 w-4 animate-spin" />
            <Send v-else class="mr-2 h-4 w-4" />
            发送
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
