<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { App } from './applications/data/schema'

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

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

const loading = ref(true)
const apps = ref<App[]>([])
const searchFilter = ref('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<App | null>(null)

const activeAppsCount = computed(() => apps.value.filter(app => app.status === 'active').length)
const totalUsers = computed(() => apps.value.reduce((sum, app) => sum + (app.users || 0), 0))
const totalVerifyCount = computed(() => apps.value.reduce((sum, app) => sum + (app.verify_count || 0), 0))

const filteredApps = computed(() => {
  if (!searchFilter.value)
    return apps.value

  const query = searchFilter.value.toLowerCase()
  return apps.value.filter(app =>
    app.name.toLowerCase().includes(query)
    || app.app_key?.toLowerCase().includes(query)
    || app.description?.toLowerCase().includes(query),
  )
})

async function fetchApps() {
  loading.value = true
  try {
    const data = await api.get<{ applications: App[] }>('/dev/applications')
    const applications = data?.applications || []
    apps.value = applications.map((app: any) => ({
      id: app.id,
      name: app.name,
      description: app.description,
      app_key: app.app_key || '',
      billing_type: app.billing_type || 'free',
      login_policy: app.login_policy || 'loose',
      enable_trial: app.enable_trial || false,
      trial_balance: app.trial_balance || 0,
      enable_free_period: app.enable_free_period || false,
      free_period_start: app.free_period_start || '',
      free_period_end: app.free_period_end || '',
      status: app.status || 'active',
      users: app.users || 0,
      devices: app.devices || 0,
      verify_count: app.verify_count || 0,
      created_at: app.created_at || new Date(),
      icon_url: app.icon_url || '',
      encrypt_type: app.encrypt_type || 'none',
      secret_key: app.secret_key || '',
      bind_type: app.bind_type || 'device',
      max_devices: app.max_devices || 1,
      multi_open: app.multi_open || false,
      deduction_cycle: app.deduction_cycle || 'per_use',
      deduction_amount: app.deduction_amount || 1,
      heartbeat_interval: app.heartbeat_interval || 60,
      heartbeat_timeout: app.heartbeat_timeout || 300,
      max_attempts: app.max_attempts || 5,
      lock_duration: app.lock_duration || 30,
      disabled_by_package: app.disabled_by_package || false,
    }))
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/developer/applications/create')
}

function goToSettings(app: App) {
  router.push(`/developer/applications/${app.id}/settings`)
}

function goToSecurity(app: App) {
  router.push(`/developer/applications/${app.id}/security`)
}

function goToEmail(app: App) {
  router.push(`/developer/applications/${app.id}/email`)
}

async function toggleStatus(app: App) {
  try {
    const newStatus = app.status === 'active' ? 'inactive' : 'active'
    await api.put(`/dev/applications/${app.id}`, { status: newStatus })
    toast.success(t('developer.applications.statusUpdateSuccess'))
    fetchApps()
  }
  catch (error: any) {
    console.error('切换应用状态失败:', error)
    toast.error(error.message || t('developer.applications.statusUpdateFailed'))
  }
}

function confirmDeleteApp(app: App) {
  deleteTarget.value = app
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/applications/${deleteTarget.value.id}`)
    toast.success(t('developer.applications.deleteSuccess'))
    fetchApps()
  }
  catch (error: any) {
    console.error('删除应用失败:', error)
    toast.error(error.message || t('developer.applications.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

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

<template>
  <BasicPage
    :title="t('developer.applications.title')"
    :description="t('developer.applications.description')"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Icon icon="lucide:plus" class="mr-2 h-4 w-4" />
        {{ t('developer.applications.createApp') }}
      </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('developer.applications.totalApps') }}
            </UiCardTitle>
            <Icon icon="lucide:layout-grid" class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ apps.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('developer.applications.activeApps') }}
            </UiCardTitle>
            <Icon icon="lucide:check-circle" class="size-4 text-green-500" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeAppsCount }}
            </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('developer.applications.totalUsers') }}
            </UiCardTitle>
            <Icon icon="lucide:users" class="size-4 text-blue-500" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalUsers }}
            </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('developer.applications.totalVerifyCount') }}
            </UiCardTitle>
            <Icon icon="lucide:activity" class="size-4 text-purple-500" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalVerifyCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            :loading
            :data="filteredApps"
            :search-filter="searchFilter"
            @refresh="fetchApps"
            @go-to-settings="goToSettings"
            @go-to-security="goToSecurity"
            @go-to-email="goToEmail"
            @toggle-status="toggleStatus"
            @delete="confirmDeleteApp"
            @update:search-filter="searchFilter = $event"
          />
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('developer.applications.delete')"
      :cancel-button-text="t('developer.applications.create.cancelBtn')"
      @confirm="handleDeleteApp"
    >
      <template #title>
        {{ t('developer.applications.deleteApp') }}
      </template>
      <template #description>
        {{ t('developer.applications.deleteAppConfirm', { name: deleteTarget?.name }) }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
