<script setup lang="ts">
import { Check, Eye, Loader2, Settings2 } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

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

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

interface Application {
  id: number
  name: string
}

const codeId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])

const form = ref({
  name: '',
  application_id: '',
  description: '',
  code: '',
  enabled: true,
})

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

const selectedApplication = computed(() => {
  if (form.value.application_id) {
    return applications.value.find(app => String(app.id) === form.value.application_id)
  }
  return null
})

async function fetchCode() {
  loading.value = true
  try {
    const data = await api.get<any>(`/dev/dynamic-codes/${codeId.value}`)
    const code = data?.dynamic_code || data
    if (code) {
      form.value.name = code.name || ''
      form.value.application_id = String(code.application_id || '')
      form.value.description = code.description || ''
      form.value.code = code.code || ''
      form.value.enabled = code.enabled !== false
    }
  }
  catch (error) {
    console.error('获取云端函数失败:', error)
    toast.error(t('admin.cloudFunction.editFailed'))
  }
  finally {
    loading.value = false
  }
}

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

async function handleSubmit() {
  if (!form.value.name.trim()) {
    toast.error(t('admin.cloudFunction.create.nameRequired'))
    return
  }
  if (!form.value.application_id) {
    toast.error(t('admin.cloudFunction.create.selectAppRequired'))
    return
  }
  if (!form.value.code.trim()) {
    toast.error(t('admin.cloudFunction.create.codeRequired'))
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/dynamic-codes/${codeId.value}`, {
      name: form.value.name,
      application_id: Number.parseInt(form.value.application_id),
      description: form.value.description,
      code: form.value.code,
      enabled: form.value.enabled,
    })
    toast.success(t('admin.cloudFunction.editSuccess'))
    router.push('/admin/cloud-function')
  }
  catch (error: any) {
    console.error('更新云端函数失败:', error)
    toast.error(error.message || t('admin.cloudFunction.editFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.cloudFunction.edit')"
    :description="t('admin.cloudFunction.create.description')"
    :breadcrumbs="[
      { title: t('admin.cloudFunction.title'), href: '/admin/cloud-function' },
      { title: t('admin.cloudFunction.edit') },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="size-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else class="space-y-6">
      <div class="grid gap-6 lg:grid-cols-3">
        <div class="lg:col-span-2 space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Settings2 class="size-5" />
                {{ t('admin.cloudFunction.create.config') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.cloudFunction.create.configDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.cloudFunction.create.application') }}
                </UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.cloudFunction.create.selectAppPlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem
                      v-for="app in filteredApplications"
                      :key="app.value"
                      :value="app.value"
                    >
                      {{ app.label }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="name">
                  {{ t('admin.cloudFunction.create.name') }}
                </UiLabel>
                <UiInput
                  id="name"
                  v-model="form.name"
                  :placeholder="t('admin.cloudFunction.create.namePlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="description">
                  {{ t('admin.cloudFunction.create.description') }}
                </UiLabel>
                <UiTextarea
                  id="description"
                  v-model="form.description"
                  :placeholder="t('admin.cloudFunction.create.descriptionPlaceholder')"
                  rows="3"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="code">
                  {{ t('admin.cloudFunction.create.code') }}
                </UiLabel>
                <UiTextarea
                  id="code"
                  v-model="form.code"
                  :placeholder="t('admin.cloudFunction.create.codePlaceholder')"
                  rows="12"
                  class="font-mono text-sm"
                />
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.cloudFunction.create.codeHelp') }}
                </p>
              </div>

              <div class="flex items-center justify-between">
                <div>
                  <p class="font-medium">
                    {{ t('admin.cloudFunction.create.enabled') }}
                  </p>
                </div>
                <UiSwitch v-model="form.enabled" />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                {{ t('admin.cloudFunction.create.preview') }}
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cloudFunction.create.name') }}</span>
                  <span>{{ form.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cloudFunction.create.application') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cloudFunction.create.description') }}</span>
                  <span class="text-right max-w-[150px] truncate">{{ form.description || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm items-center">
                  <span class="text-muted-foreground">{{ t('admin.cloudFunction.create.status') }}</span>
                  <UiSwitch v-model="form.enabled" />
                </div>
                <div class="border-t pt-3 mt-3">
                  <div class="text-sm">
                    <div class="text-muted-foreground mb-2">
                      {{ t('admin.cloudFunction.create.code') }}
                    </div>
                    <div class="font-mono text-xs bg-muted p-2 rounded max-h-[150px] overflow-auto" style="white-space: pre-wrap;">{{ form.code || '-' }}</div>
                  </div>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardContent class="pt-6">
              <div class="flex flex-col gap-3">
                <UiButton
                  class="w-full"
                  size="lg"
                  :disabled="saving || !form.name || !form.application_id || !form.code"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Check v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.cloudFunction.create.saveBtn') || '保存修改' }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.push('/admin/cloud-function')"
                >
                  {{ t('admin.cloudFunction.create.cancelBtn') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
