<script setup lang="ts">
import { Check, Eye, File, Loader2, Settings2, Upload, X } 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 constantId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])
const fileInput = ref<HTMLInputElement | null>(null)
const selectedFile = ref<File | null>(null)
const uploading = ref(false)

const form = ref({
  app_id: '',
  key: '',
  value: '',
  var_type: 'string',
  description: '',
  status: 'active',
})

async function fetchConstant() {
  loading.value = true
  try {
    const data = await api.get<any>(`/dev/cloud-constants/${constantId.value}`)
    const ct = data?.cloud_constant || data
    if (ct) {
      form.value.app_id = String(ct.app_id || '')
      form.value.key = ct.key || ''
      form.value.value = ct.value || ''
      form.value.var_type = ct.var_type || 'string'
      form.value.description = ct.description || ''
      form.value.status = ct.status || 'active'
    }
  }
  catch (error) {
    console.error('获取云端常量失败:', error)
    toast.error(t('admin.cloudConstants.editFailed'))
  }
  finally {
    loading.value = false
  }
}

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)
  }
}

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

function handleFileSelect(event: Event) {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    selectedFile.value = target.files[0]
  }
}

function clearFile() {
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

async function handleSave() {
  if (!form.value.key) {
    toast.error(t('admin.cloudConstants.create.keyRequired'))
    return
  }
  if (!form.value.app_id) {
    toast.error(t('admin.cloudConstants.create.appRequired'))
    return
  }

  if (form.value.var_type === 'binary') {
    if (!selectedFile.value) {
      toast.error('请选择要上传的文件')
      return
    }
    await uploadFile()
    return
  }

  if (!form.value.value) {
    toast.error(t('admin.cloudConstants.create.valueRequired'))
    return
  }

  saving.value = true
  try {
    await api.put(`/dev/cloud-constants/${constantId.value}`, {
      app_id: Number(form.value.app_id),
      key: form.value.key,
      value: form.value.value,
      var_type: form.value.var_type,
      description: form.value.description,
      status: form.value.status,
    })
    toast.success(t('admin.cloudConstants.editSuccess'))
    router.push('/admin/cloud-constants')
  }
  catch (error: any) {
    console.error('更新云端常量失败:', error)
    toast.error(error.message || t('admin.cloudConstants.editFailed'))
  }
  finally {
    saving.value = false
  }
}

async function uploadFile() {
  if (!selectedFile.value || !form.value.app_id || !form.value.key)
    return

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('app_id', form.value.app_id)
    formData.append('key', form.value.key)
    formData.append('description', form.value.description)
    formData.append('status', form.value.status)

    await api.postFormData(`/dev/cloud-constants/${constantId.value}/upload`, formData)
    toast.success(t('admin.cloudConstants.editSuccess'))
    router.push('/admin/cloud-constants')
  }
  catch (error: any) {
    console.error('上传文件失败:', error)
    toast.error(error.message || '上传文件失败')
  }
  finally {
    uploading.value = false
  }
}

function formatFileSize(bytes: number): string {
  if (bytes === 0)
    return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}

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

<template>
  <BasicPage
    :title="t('admin.cloudConstants.edit')"
    :description="t('admin.cloudConstants.createDescription')"
    :breadcrumbs="[
      { title: t('admin.cloudConstants.title'), href: '/admin/cloud-constants' },
      { title: t('admin.cloudConstants.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.cloudConstants.create.config') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.cloudConstants.create.configDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.cloudConstants.create.application') }}
                </UiLabel>
                <UiSelect v-model="form.app_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.cloudConstants.create.selectApp')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in applications" :key="app.id" :value="String(app.id)">
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

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

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

              <div v-if="form.var_type === 'binary'" class="space-y-2">
                <UiLabel>选择文件</UiLabel>
                <div v-if="!selectedFile" class="border-2 border-dashed rounded-lg p-6 text-center">
                  <input
                    ref="fileInput"
                    type="file"
                    class="hidden"
                    @change="handleFileSelect"
                  >
                  <Upload class="mx-auto h-12 w-12 text-muted-foreground mb-4" />
                  <p class="text-sm text-muted-foreground mb-2">
                    拖拽文件到此处或点击选择
                  </p>
                  <UiButton variant="outline" @click="fileInput?.click()">
                    选择文件
                  </UiButton>
                </div>
                <div v-else class="border rounded-lg p-4">
                  <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                      <File class="h-8 w-8 text-muted-foreground" />
                      <div>
                        <p class="font-medium">
                          {{ selectedFile.name }}
                        </p>
                        <p class="text-sm text-muted-foreground">
                          {{ formatFileSize(selectedFile.size) }}
                        </p>
                      </div>
                    </div>
                    <UiButton variant="ghost" size="icon" @click="clearFile">
                      <X class="h-4 w-4" />
                    </UiButton>
                  </div>
                </div>
              </div>

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

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

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                {{ t('admin.cloudConstants.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.cloudConstants.create.application') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cloudConstants.create.type') }}</span>
                  <span>{{ t(`admin.cloudConstants.types.${form.var_type}`) }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.cloudConstants.create.key') }}</span>
                  <span>{{ form.key || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm items-center">
                  <span class="text-muted-foreground">{{ t('admin.cloudConstants.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('admin.cloudConstants.create.value') }}
                    </div>
                    <div v-if="form.var_type === 'binary'" class="bg-muted p-2 rounded text-xs">
                      {{ selectedFile ? `${selectedFile.name} (${formatFileSize(selectedFile.size)})` : '未选择文件' }}
                    </div>
                    <div v-else class="bg-muted p-2 rounded max-h-[100px] overflow-y-auto text-xs">
                      {{ form.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 || uploading) || !form.app_id || !form.key || (form.var_type !== 'binary' && !form.value) || (form.var_type === 'binary' && !selectedFile)"
                  @click="handleSave"
                >
                  <Loader2 v-if="saving || uploading" class="mr-2 h-4 w-4 animate-spin" />
                  <Check v-else class="mr-2 h-4 w-4" />
                  {{ uploading ? '上传中...' : t('admin.cloudConstants.create.submit') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.cloudConstants.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
