<script setup lang="ts">
import { Code, Eye, Loader2 } from 'lucide-vue-next'
import { onMounted, ref } from 'vue'

const API_BASE = 'http://localhost:8080/api/v1'

interface DynamicCode {
  id: string
  name: string
  code: string
  description: string
  applicationId: string
  appName: string
  enabled: boolean
  createdAt: string
  updatedAt: string
}

interface Application {
  id: string
  name: string
}

const loading = ref(true)
const codes = ref<DynamicCode[]>([])
const applications = ref<Application[]>([])
const selectedCode = ref<DynamicCode | null>(null)
const showCodeDialog = ref(false)

async function fetchCodes() {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/dynamic-codes`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      codes.value = data.data || []
    }
  }
  catch (error) {
    console.error('获取云端函数失败:', error)
  }
  finally {
    loading.value = false
  }
}

async function fetchApplications() {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/applications`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    const data = await response.json()
    if (data.code === 200) {
      applications.value = data.data || []
    }
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

function formatDate(date: string) {
  return new Date(date).toLocaleString('zh-CN')
}

function openCodeDialog(code: DynamicCode) {
  selectedCode.value = code
  showCodeDialog.value = true
}

async function toggleCodeStatus(code: DynamicCode) {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/dynamic-codes/${code.id}/status`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ enabled: !code.enabled }),
    })

    const data = await response.json()
    if (data.code === 200) {
      fetchCodes()
    }
  }
  catch (error) {
    console.error('切换云端函数状态失败:', error)
  }
}

onMounted(() => {
  fetchCodes()
  fetchApplications()
})
</script>

<template>
  <BasicPage
    title="云端函数"
    description="管理应用的云端函数配置"
  >
    <div class="space-y-6">
      <UiCard>
        <UiCardContent class="p-4 sm:p-6">
          <div v-if="loading" class="text-center py-12">
            <Loader2 class="h-8 w-8 animate-spin mx-auto text-muted-foreground" />
            <p class="mt-2 text-muted-foreground">
              加载中...
            </p>
          </div>

          <div v-else-if="codes.length === 0" class="text-center py-8 text-muted-foreground">
            <Code class="mx-auto h-12 w-12 text-muted-foreground mb-2" />
            <p>暂无云端函数</p>
          </div>

          <div v-else class="space-y-4">
            <div
              v-for="code in codes"
              :key="code.id"
              class="border rounded-lg p-4 space-y-3"
              :class="code.enabled ? 'bg-card' : 'bg-muted/30'"
            >
              <div class="flex items-start justify-between">
                <div class="flex items-center space-x-3">
                  <div class="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Code class="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <p class="font-medium">
                      {{ code.name }}
                    </p>
                    <p class="text-sm text-muted-foreground">
                      {{ code.appName }}
                    </p>
                  </div>
                </div>
                <div class="flex items-center gap-2">
                  <UiBadge :variant="code.enabled ? 'default' : 'secondary'">
                    {{ code.enabled ? '已启用' : '已禁用' }}
                  </UiBadge>
                  <UiButton variant="outline" size="sm" @click="toggleCodeStatus(code)">
                    {{ code.enabled ? '禁用' : '启用' }}
                  </UiButton>
                  <UiButton variant="outline" size="sm" @click="openCodeDialog(code)">
                    <Eye class="h-4 w-4 mr-1" />
                    查看代码
                  </UiButton>
                </div>
              </div>

              <div v-if="code.description" class="text-sm text-muted-foreground">
                {{ code.description }}
              </div>

              <div class="flex items-center justify-between text-xs text-muted-foreground">
                <span>创建时间: {{ formatDate(code.createdAt) }}</span>
                <span>更新时间: {{ formatDate(code.updatedAt) }}</span>
              </div>
            </div>
          </div>
        </UiCardContent>
      </UiCard>
    </div>

    <UiDialog v-model:open="showCodeDialog">
      <UiDialogContent class="w-[95vw] sm:max-w-4xl max-h-[90vh] overflow-y-auto">
        <UiDialogHeader>
          <UiDialogTitle>{{ selectedCode?.name }}</UiDialogTitle>
          <UiDialogDescription>云端函数详情</UiDialogDescription>
        </UiDialogHeader>
        <div class="py-4">
          <div class="bg-muted rounded-lg p-4">
            <pre class="text-sm font-mono whitespace-pre-wrap break-all">{{ selectedCode?.code }}</pre>
          </div>
        </div>
        <UiDialogFooter>
          <UiButton @click="showCodeDialog = false">
            关闭
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
