<script setup lang="ts">
import { Cloud, Database, Eye, Globe, Variable } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

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

interface Application {
  id: number
  name: string
  app_key: string
}

const loading = ref(true)
const activeTab = ref('variables')
const applications = ref<Application[]>([])
const appFilter = ref<string>('')

const variables = ref<any[]>([])
const constants = ref<any[]>([])

const filteredVariables = computed(() => {
  if (!appFilter.value) return variables.value
  return variables.value.filter(v => String(v.app_id) === appFilter.value)
})

const filteredConstants = computed(() => {
  if (!appFilter.value) return constants.value
  return constants.value.filter(c => String(c.app_id) === appFilter.value)
})

const stats = computed(() => ({
  variables: variables.value.length,
  constants: constants.value.length,
  applications: applications.value.length,
}))

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/agent/applications')
    applications.value = data?.applications || []
  }
  catch { /* ignore */ }
}

async function fetchVariables() {
  try {
    const data = await api.get<{ variables: any[] }>('/agent/cloud-variables')
    variables.value = data?.variables || []
  }
  catch {
    variables.value = []
  }
}

async function fetchConstants() {
  try {
    const data = await api.get<{ constants: any[] }>('/agent/cloud-constants')
    constants.value = data?.constants || []
  }
  catch {
    constants.value = []
  }
}

function getAppName(appId: number) {
  const app = applications.value.find(a => a.id === appId)
  return app?.name || String(appId)
}

function formatDate(dateStr: string) {
  if (!dateStr) return '-'
  return dateStr.replace('T', ' ').substring(0, 19)
}

onMounted(async () => {
  loading.value = true
  await Promise.all([fetchApplications(), fetchVariables(), fetchConstants()])
  loading.value = false
})
</script>

<template>
  <BasicPage
    title="云端数据"
    description="查看云端变量和常量数据（只读）"
    :breadcrumbs="[
      { title: '控制台', href: '/agent' },
      { title: '云端数据' },
    ]"
  >
    <div class="space-y-6">
      <div class="grid gap-4 md:grid-cols-3">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">云端变量</UiCardTitle>
            <Variable class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">{{ stats.variables }}</div>
          </UiCardContent>
        </UiCard>
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">云端常量</UiCardTitle>
            <Database class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">{{ stats.constants }}</div>
          </UiCardContent>
        </UiCard>
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">应用数量</UiCardTitle>
            <Globe class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">{{ stats.applications }}</div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardHeader>
          <div class="flex items-center justify-between">
            <div>
              <UiCardTitle class="flex items-center gap-2">
                <Cloud class="size-5" />
                数据列表
              </UiCardTitle>
              <UiCardDescription>只读模式，数据不可编辑</UiCardDescription>
            </div>
            <div class="flex items-center gap-3">
              <UiSelect v-model="appFilter">
                <UiSelectTrigger class="w-[180px]">
                  <UiSelectValue placeholder="全部应用" />
                </UiSelectTrigger>
                <UiSelectContent>
                  <UiSelectItem value="all">全部应用</UiSelectItem>
                  <UiSelectItem v-for="app in applications" :key="app.id" :value="String(app.id)">
                    {{ app.name }}
                  </UiSelectItem>
                </UiSelectContent>
              </UiSelect>
              <div class="flex border rounded-lg overflow-hidden">
                <button
                  class="px-4 py-2 text-sm font-medium transition-colors"
                  :class="activeTab === 'variables' ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'"
                  @click="activeTab = 'variables'"
                >
                  云端变量
                </button>
                <button
                  class="px-4 py-2 text-sm font-medium transition-colors"
                  :class="activeTab === 'constants' ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'"
                  @click="activeTab = 'constants'"
                >
                  云端常量
                </button>
              </div>
            </div>
          </div>
        </UiCardHeader>
        <UiCardContent>
          <div v-if="loading" class="flex items-center justify-center py-12">
            <div class="size-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          </div>

          <template v-else>
            <div v-if="activeTab === 'variables'">
              <div v-if="filteredVariables.length === 0" class="text-center py-12 text-muted-foreground">
                暂无云端变量数据
              </div>
              <div v-else class="border rounded-lg overflow-hidden">
                <div class="overflow-x-auto">
                  <table class="w-full text-sm">
                    <thead class="bg-muted/50">
                      <tr>
                        <th class="text-left p-3 font-medium">名称</th>
                        <th class="text-left p-3 font-medium">应用</th>
                        <th class="text-left p-3 font-medium">作用域</th>
                        <th class="text-left p-3 font-medium">状态</th>
                        <th class="text-left p-3 font-medium">创建时间</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="v in filteredVariables" :key="v.id" class="border-t hover:bg-muted/30 transition-colors">
                        <td class="p-3 font-medium">{{ v.name }}</td>
                        <td class="p-3 text-muted-foreground">{{ getAppName(v.app_id) }}</td>
                        <td class="p-3">
                          <UiBadge variant="outline">{{ v.scope || 'global' }}</UiBadge>
                        </td>
                        <td class="p-3">
                          <UiBadge :variant="v.status === 1 ? 'default' : 'secondary'">
                            {{ v.status === 1 ? '启用' : '禁用' }}
                          </UiBadge>
                        </td>
                        <td class="p-3 text-muted-foreground">{{ formatDate(v.created_at) }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <div v-if="activeTab === 'constants'">
              <div v-if="filteredConstants.length === 0" class="text-center py-12 text-muted-foreground">
                暂无云端常量数据
              </div>
              <div v-else class="border rounded-lg overflow-hidden">
                <div class="overflow-x-auto">
                  <table class="w-full text-sm">
                    <thead class="bg-muted/50">
                      <tr>
                        <th class="text-left p-3 font-medium">名称</th>
                        <th class="text-left p-3 font-medium">应用</th>
                        <th class="text-left p-3 font-medium">值</th>
                        <th class="text-left p-3 font-medium">状态</th>
                        <th class="text-left p-3 font-medium">创建时间</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="c in filteredConstants" :key="c.id" class="border-t hover:bg-muted/30 transition-colors">
                        <td class="p-3 font-medium">{{ c.name }}</td>
                        <td class="p-3 text-muted-foreground">{{ getAppName(c.app_id) }}</td>
                        <td class="p-3 text-muted-foreground max-w-[200px] truncate">{{ c.value }}</td>
                        <td class="p-3">
                          <UiBadge :variant="c.status === 1 ? 'default' : 'secondary'">
                            {{ c.status === 1 ? '启用' : '禁用' }}
                          </UiBadge>
                        </td>
                        <td class="p-3 text-muted-foreground">{{ formatDate(c.created_at) }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </template>

          <div class="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
            <Eye class="size-4" />
            <span>只读模式 - 当前数据仅供查看，无法进行编辑操作</span>
          </div>
        </UiCardContent>
      </UiCard>
    </div>
  </BasicPage>
</template>
