<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

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

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

interface Application {
  id: number
  name: string
}

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 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]
    if (!form.value.key) {
      form.value.key = selectedFile.value.name.replace(/\.[^/.]+$/, '')
    }
  }
}

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

async function handleSave() {
  if (!form.value.key) {
    toast.error(t('developer.cloudConstants.create.keyRequired'))
    return
  }
  if (!form.value.app_id) {
    toast.error(t('developer.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('developer.cloudConstants.create.valueRequired'))
    return
  }

  saving.value = true
  try {
    await api.post('/dev/cloud-constants', {
      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('developer.cloudConstants.create.success'))
    router.push('/developer/cloud-constants')
  }
  catch (error: any) {
    console.error('创建云端常量失败:', error)
    toast.error(error.message || t('developer.cloudConstants.create.failed'))
  }
  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/upload', formData)
    toast.success(t('developer.cloudConstants.create.success'))
    router.push('/developer/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()
})
</script>

<template>
  <BasicPage
    :title="t('developer.cloudConstants.addConstant')"
    :description="t('developer.cloudConstants.createDescription')"
    :breadcrumbs="[
      { title: t('developer.cloudConstants.title'), href: '/developer/cloud-constants' },
      { title: t('developer.cloudConstants.addConstant') },
    ]"
    sticky
  >
    <div 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.cloudConstants.create.config') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('developer.cloudConstants.create.configDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('developer.cloudConstants.create.application') }}
                </UiLabel>
                <UiSelect v-model="form.app_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('developer.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('developer.cloudConstants.create.type') }}
                </UiLabel>
                <UiSelect id="varType" v-model="form.var_type">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('developer.cloudConstants.create.selectType')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="integer">
                      {{ t('developer.cloudConstants.types.integer') }}
                    </UiSelectItem>
                    <UiSelectItem value="decimal">
                      {{ t('developer.cloudConstants.types.decimal') }}
                    </UiSelectItem>
                    <UiSelectItem value="string">
                      {{ t('developer.cloudConstants.types.string') }}
                    </UiSelectItem>
                    <UiSelectItem value="binary">
                      二进制
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="key">
                  {{ t('developer.cloudConstants.create.key') }}
                </UiLabel>
                <UiInput id="key" v-model="form.key" :placeholder="t('developer.cloudConstants.create.keyPlaceholder')" />
                <p class="text-xs text-muted-foreground">
                  {{ t('developer.cloudConstants.create.keyHint') }}
                </p>
              </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"
                  >
                  <Icon icon="lucide: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">
                      <Icon icon="lucide: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">
                      <Icon icon="lucide:x" class="h-4 w-4" />
                    </UiButton>
                  </div>
                </div>
              </div>

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

              <div class="space-y-2">
                <UiLabel for="description">
                  {{ t('developer.cloudConstants.create.description') }}
                </UiLabel>
                <UiInput id="description" v-model="form.description" :placeholder="t('developer.cloudConstants.create.descriptionPlaceholder')" />
              </div>
            </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.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('developer.cloudConstants.create.application') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('developer.cloudConstants.create.type') }}</span>
                  <span>{{ t(`developer.cloudConstants.types.${form.var_type}`) }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('developer.cloudConstants.create.key') }}</span>
                  <span>{{ form.key || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm items-center">
                  <span class="text-muted-foreground">{{ t('developer.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('developer.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"
                >
                  <Icon v-if="saving || uploading" 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" />
                  {{ uploading ? '上传中...' : t('developer.cloudConstants.create.submit') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('developer.cloudConstants.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
