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

import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

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

interface Application {
  id: number
  name: string
}

interface CloudVariable {
  id: number
  key: string
  app_id: number | null
  application_name: string
  default_value: string
  var_type: string
  max_records: number
  scope: string
  write_permission: string
  status: string
  description: string
  created_at: string
}

const loading = ref(true)
const variables = ref<CloudVariable[]>([])
const applications = ref<Application[]>([])

const appFilter = ref<string>('')
const scopeFilter = ref<string>('')

const filteredVariables = computed(() => {
  let result = [...variables.value]
  if (appFilter.value) {
    result = result.filter(v => String(v.app_id) === appFilter.value)
  }
  if (scopeFilter.value) {
    result = result.filter(v => v.scope === scopeFilter.value)
  }
  return result
})

const appScopeCount = computed(() => variables.value.filter(v => v.scope === 'app').length)
const userScopeCount = computed(() => variables.value.filter(v => v.scope === 'user').length)

const applicationOptions = computed(() =>
  applications.value.map(app => ({ label: app.name, value: String(app.id) })),
)

const scopeOptions = computed(() => [
  { label: t('agent.cloudVariables.appScope'), value: 'app' },
  { label: t('agent.cloudVariables.userScope'), value: 'user' },
])

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

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

function handleViewRecords(variable: CloudVariable) {
  router.push(`/agent/cloud-variables/${variable.id}/records?app_id=${variable.app_id}`)
}

function formatDate(dateStr: string) {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    if (Number.isNaN(date.getTime())) return '-'
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }
  catch {
    return '-'
  }
}

function formatVarType(type: string) {
  const map: Record<string, string> = {
    integer: t('agent.cloudVariables.types.integer'),
    decimal: t('agent.cloudVariables.types.decimal'),
    string: t('agent.cloudVariables.types.string'),
    binary: t('agent.cloudVariables.types.binary'),
    stream: t('agent.cloudVariables.types.stream'),
  }
  return map[type || 'string'] || type || 'string'
}

onMounted(async () => {
  await fetchApplications()
  fetchVariables()
})
</script>

<template>
  <BasicPage
    :title="t('agent.cloudVariables.title')"
    :description="t('agent.cloudVariables.description')"
    :breadcrumbs="[
      { title: t('nav.dashboard'), href: '/agent' },
      { title: t('nav.cloudVariables') },
    ]"
  >
    <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('agent.cloudVariables.totalVariables') }}
            </UiCardTitle>
            <Variable class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredVariables.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('agent.cloudVariables.appScopeVariables') }}
            </UiCardTitle>
            <Globe class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ appScopeCount }}
            </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('agent.cloudVariables.userScopeVariables') }}
            </UiCardTitle>
            <User class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ userScopeCount }}
            </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('agent.cloudVariables.appCount') }}
            </UiCardTitle>
            <LayoutGrid class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ applications.length }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <div class="mb-4 flex flex-wrap items-center gap-2">
            <SingleFilter
              v-model="appFilter"
              :title="t('agent.cloudVariables.application')"
              :options="applicationOptions"
            />
            <SingleFilter
              v-model="scopeFilter"
              :title="t('agent.cloudVariables.scope')"
              :options="scopeOptions"
            />
          </div>

          <div v-if="loading" class="flex items-center justify-center py-12">
            <div class="size-8 animate-spin rounded-full border-4 border-muted border-t-primary" />
          </div>

          <div v-else-if="filteredVariables.length === 0" class="text-center py-12 text-muted-foreground">
            {{ t('agent.cloudVariables.noVariables') }}
          </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">
                      {{ t('agent.cloudVariables.columns.key') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('agent.cloudVariables.columns.defaultValue') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('agent.cloudVariables.columns.type') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('agent.cloudVariables.columns.scope') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('agent.cloudVariables.columns.application') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('agent.cloudVariables.columns.status') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('agent.cloudVariables.columns.createdAt') }}
                    </th>
                    <th class="text-left p-3 font-medium">
                      {{ t('common.actions') }}
                    </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">
                      <code class="text-xs bg-muted px-2 py-1 rounded font-mono">{{ v.key }}</code>
                    </td>
                    <td class="p-3 text-muted-foreground max-w-[200px] truncate">
                      {{ v.default_value || '-' }}
                    </td>
                    <td class="p-3">
                      <UiBadge variant="outline">
                        {{ formatVarType(v.var_type) }}
                      </UiBadge>
                    </td>
                    <td class="p-3">
                      <UiBadge :variant="v.scope === 'app' ? 'default' : 'secondary'">
                        {{ v.scope === 'app' ? t('agent.cloudVariables.appScope') : t('agent.cloudVariables.userScope') }}
                      </UiBadge>
                    </td>
                    <td class="p-3">
                      <UiBadge v-if="v.application_name" variant="outline">
                        {{ v.application_name }}
                      </UiBadge>
                      <span v-else class="text-muted-foreground">-</span>
                    </td>
                    <td class="p-3">
                      <UiBadge :variant="v.status === 'active' ? 'default' : 'destructive'">
                        {{ v.status === 'active' ? t('agent.cloudVariables.statusActive') : t('agent.cloudVariables.statusInactive') }}
                      </UiBadge>
                    </td>
                    <td class="p-3 text-muted-foreground whitespace-nowrap">
                      {{ formatDate(v.created_at) }}
                    </td>
                    <td class="p-3">
                      <UiButton
                        v-if="v.var_type === 'stream'"
                        variant="ghost"
                        size="sm"
                        @click="handleViewRecords(v)"
                      >
                        <List class="mr-1 size-4" />
                        {{ t('agent.cloudVariables.viewRecords') }}
                      </UiButton>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </UiCardContent>
      </UiCard>
    </div>
  </BasicPage>
</template>
