<script setup lang="ts">
import { Icon } from '@iconify/vue'
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 { t } = useI18n()
const route = useRoute()
const router = useRouter()

interface Application {
  id: number
  name: string
}

const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])

const form = ref({
  id: '',
  app_id: '',
  key: '',
  default_value: '',
  var_type: 'string',
  scope: 'app',
  write_permission: 'admin',
  description: '',
  status: 'active',
})

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

async function fetchVariable() {
  loading.value = true
  try {
    const varId = route.params.id
    const data = await api.get<{ id: number, app_id: number, key: string, default_value: string, var_type: string, scope: string, write_permission: string, description: string, status: string }>(`/dev/cloud-variables/${varId}`)
    const variable = data
    if (variable) {
      form.value = {
        id: String(variable.id),
        app_id: String(variable.app_id || ''),
        key: variable.key,
        default_value: variable.default_value || '',
        var_type: variable.var_type || 'string',
        scope: variable.scope || 'app',
        write_permission: variable.write_permission || 'admin',
        description: variable.description || '',
        status: variable.status || 'active',
      }
    }
    else {
      toast.error(t('developer.cloudVariables.create.failed'))
      router.push('/developer/cloud-variables')
    }
  }
  catch (error) {
    console.error('获取云端变量失败:', error)
    toast.error(t('developer.cloudVariables.create.failed'))
    router.push('/developer/cloud-variables')
  }
  finally {
    loading.value = false
  }
}

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

async function handleSave() {
  if (!form.value.key) {
    toast.error(t('developer.cloudVariables.create.keyRequired'))
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/cloud-variables/${form.value.id}`, {
      key: form.value.key,
      default_value: form.value.default_value,
      var_type: form.value.var_type,
      write_permission: form.value.write_permission,
      description: form.value.description,
      status: form.value.status,
    })
    toast.success(t('developer.cloudVariables.create.success'))
    router.push('/developer/cloud-variables')
  }
  catch (error: any) {
    console.error('更新云端变量失败:', error)
    toast.error(error.message || t('developer.cloudVariables.create.failed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('developer.cloudVariables.edit')"
    :description="t('developer.cloudVariables.editDescription')"
    :breadcrumbs="[
      { title: t('developer.cloudVariables.title'), href: '/developer/cloud-variables' },
      { title: t('developer.cloudVariables.edit') },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-12">
      <Icon icon="lucide:loader-2" 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">
                <Icon icon="lucide:settings-2" class="size-5" />
                {{ t('developer.cloudVariables.create.config') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('developer.cloudVariables.create.configDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel>{{ t('developer.cloudVariables.create.application') }}</UiLabel>
                <div class="flex items-center gap-2 p-2.5 rounded-md border bg-muted/50">
                  <Icon icon="lucide:layout-grid" class="size-4 text-muted-foreground" />
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel for="varType">
                  {{ t('developer.cloudVariables.create.type') }}
                </UiLabel>
                <UiSelect id="varType" v-model="form.var_type">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('developer.cloudVariables.create.selectType')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="integer">
                      {{ t('developer.cloudVariables.types.integer') }}
                    </UiSelectItem>
                    <UiSelectItem value="decimal">
                      {{ t('developer.cloudVariables.types.decimal') }}
                    </UiSelectItem>
                    <UiSelectItem value="string">
                      {{ t('developer.cloudVariables.types.string') }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="key">
                  {{ t('developer.cloudVariables.create.key') }}
                </UiLabel>
                <UiInput id="key" v-model="form.key" :placeholder="t('developer.cloudVariables.create.keyPlaceholder')" />
                <p class="text-xs text-muted-foreground">
                  {{ t('developer.cloudVariables.create.keyHint') }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel for="defaultValue">
                  {{ t('developer.cloudVariables.create.defaultValue') }}
                </UiLabel>
                <UiTextarea id="defaultValue" v-model="form.default_value" :placeholder="t('developer.cloudVariables.create.defaultValuePlaceholder')" rows="3" />
              </div>

              <div class="space-y-2">
                <UiLabel for="description">
                  {{ t('developer.cloudVariables.create.description') }}
                </UiLabel>
                <UiInput id="description" v-model="form.description" :placeholder="t('developer.cloudVariables.create.descriptionPlaceholder')" />
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle>{{ t('developer.cloudVariables.create.scopeTitle') }}</UiCardTitle>
              <UiCardDescription>{{ t('developer.cloudVariables.create.scopeDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent>
              <div
                class="flex items-start gap-3 p-4 rounded-lg border"
                :class="form.scope === 'app' ? 'border-blue-500 bg-blue-50 dark:bg-blue-950/30' : 'border-purple-500 bg-purple-50 dark:bg-purple-950/30'"
              >
                <Icon
                  :icon="form.scope === 'app' ? 'lucide:globe' : 'lucide:user'"
                  class="size-5 mt-0.5"
                  :class="form.scope === 'app' ? 'text-blue-500' : 'text-purple-500'"
                />
                <div>
                  <p class="font-medium">
                    {{ form.scope === 'app' ? t('developer.cloudVariables.create.appScope') : t('developer.cloudVariables.create.userScope') }}
                  </p>
                  <p class="text-sm text-muted-foreground mt-1">
                    {{ form.scope === 'app' ? t('developer.cloudVariables.create.appScopeDesc') : t('developer.cloudVariables.create.userScopeDesc') }}
                  </p>
                </div>
              </div>
              <p class="text-xs text-muted-foreground mt-2">
                {{ t('developer.cloudVariables.create.scopeImmutable') }}
              </p>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle>{{ t('developer.cloudVariables.create.permissionTitle') }}</UiCardTitle>
              <UiCardDescription>{{ t('developer.cloudVariables.create.permissionDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent>
              <UiRadioGroup v-model="form.write_permission" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div
                  class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                  :class="form.write_permission === 'admin' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.write_permission = 'admin'"
                >
                  <UiRadioGroupItem value="admin" class="mt-0.5" />
                  <div>
                    <div class="flex items-center gap-2">
                      <Icon icon="lucide:lock" class="size-4 text-primary" />
                      <p class="font-medium">
                        {{ t('developer.cloudVariables.create.developerOnly') }}
                      </p>
                    </div>
                    <p class="text-sm text-muted-foreground mt-1">
                      {{ form.scope === 'app' ? t('developer.cloudVariables.create.developerOnlyAppDesc') : t('developer.cloudVariables.create.developerOnlyDesc') }}
                    </p>
                  </div>
                </div>

                <div
                  class="flex items-start gap-3 p-4 rounded-lg border cursor-pointer transition-colors"
                  :class="form.write_permission === 'user' ? 'border-primary bg-primary/5' : 'hover:bg-accent'"
                  @click="form.write_permission = 'user'"
                >
                  <UiRadioGroupItem value="user" class="mt-0.5" />
                  <div>
                    <div class="flex items-center gap-2">
                      <Icon icon="lucide:unlock" class="size-4 text-primary" />
                      <p class="font-medium">
                        {{ t('developer.cloudVariables.create.userWritable') }}
                      </p>
                    </div>
                    <p class="text-sm text-muted-foreground mt-1">
                      {{ form.scope === 'app' ? t('developer.cloudVariables.create.userWritableAppDesc') : t('developer.cloudVariables.create.userWritableDesc') }}
                    </p>
                  </div>
                </div>
              </UiRadioGroup>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Icon icon="lucide:eye" class="size-5" />
                {{ t('developer.cloudVariables.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('developer.cloudVariables.create.application') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('developer.cloudVariables.create.type') }}</span>
                  <span>{{ t(`developer.cloudVariables.types.${form.var_type}`) }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('developer.cloudVariables.create.key') }}</span>
                  <span>{{ form.key || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('developer.cloudVariables.create.scope') }}</span>
                  <UiBadge variant="outline">
                    {{ form.scope === 'app' ? t('developer.cloudVariables.appScope') : t('developer.cloudVariables.userScope') }}
                  </UiBadge>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('developer.cloudVariables.create.writePermission') }}</span>
                  <UiBadge variant="secondary">
                    {{ form.write_permission === 'admin' ? t('developer.cloudVariables.create.developerOnly') : t('developer.cloudVariables.create.userWritable') }}
                  </UiBadge>
                </div>
                <div class="flex justify-between text-sm items-center">
                  <span class="text-muted-foreground">{{ t('developer.cloudVariables.create.status') }}</span>
                  <UiSwitch
                    :checked="form.status === 'active'"
                    @update:checked="form.status = $event ? 'active' : 'inactive'"
                  />
                </div>
                <div class="border-t pt-3 mt-3">
                  <div class="text-sm">
                    <div class="text-muted-foreground mb-2">
                      {{ t('developer.cloudVariables.create.defaultValue') }}
                    </div>
                    <div class="bg-muted p-2 rounded max-h-[100px] overflow-y-auto text-xs">
                      {{ form.default_value || '-' }}
                    </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.key"
                  @click="handleSave"
                >
                  <Icon v-if="saving" icon="lucide:loader-2" class="mr-2 h-4 w-4 animate-spin" />
                  <Icon v-else icon="lucide:check" class="mr-2 h-4 w-4" />
                  {{ t('developer.cloudVariables.create.submit') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('developer.cloudVariables.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
