<script setup lang="ts">
import { Cloud, Database, Eye, Folder, Globe, HardDrive, Loader2, Lock, Plug, Plus } from 'lucide-vue-next'
import { computed, ref } from 'vue'
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 saving = ref(false)
const testing = ref(false)

const formData = ref({
  name: '',
  type: 'local' as 'local' | 's3' | 'webdav' | 'ftp' | 'sftp',
  endpoint: '',
  bucket: '',
  access_key: '',
  secret_key: '',
  region: '',
  path_prefix: '',
  is_default: false,
  status: 'active' as 'active' | 'inactive',
  remark: '',
})

const storageTypes = [
  { value: 'local', label: '本地存储', icon: HardDrive, description: '存储在服务器本地磁盘' },
  { value: 's3', label: 'S3存储', icon: Cloud, description: '兼容S3协议的对象存储' },
  { value: 'webdav', label: 'WebDAV', icon: Globe, description: 'WebDAV协议存储' },
  { value: 'ftp', label: 'FTP', icon: Folder, description: 'FTP协议存储' },
  { value: 'sftp', label: 'SFTP', icon: Lock, description: 'SFTP协议存储' },
]

const selectedType = computed(() => {
  return storageTypes.find(t => t.value === formData.value.type)
})

const isLocal = computed(() => formData.value.type === 'local')
const isS3 = computed(() => formData.value.type === 's3')

const endpointPlaceholder = computed(() => {
  switch (formData.value.type) {
    case 's3':
      return 's3.amazonaws.com'
    case 'webdav':
      return 'https://webdav.example.com'
    case 'ftp':
    case 'sftp':
      return 'ftp.example.com:21'
    default:
      return ''
  }
})

async function handleTest() {
  if (!formData.value.endpoint && !isLocal.value) {
    toast.error('请先填写端点地址')
    return
  }

  testing.value = true
  try {
    await api.post('/dev/storage-configs/test', formData.value)
    toast.success('连接测试成功')
  }
  catch (error: any) {
    console.error('连接测试失败:', error)
    toast.error(error.message || '连接失败')
  }
  finally {
    testing.value = false
  }
}

async function handleSubmit() {
  if (!formData.value.name) {
    toast.error('请输入存储名称')
    return
  }

  saving.value = true
  try {
    await api.post('/dev/storage-configs', formData.value)
    toast.success('创建成功')
    router.push('/admin/storage-configs')
  }
  catch (error: any) {
    console.error('创建存储配置失败:', error)
    toast.error(error.message || '创建失败')
  }
  finally {
    saving.value = false
  }
}
</script>

<template>
  <BasicPage
    title="添加存储配置"
    description="配置新的存储方式"
    :breadcrumbs="[
      { title: '存储管理', href: '/admin/storage-configs' },
      { title: '添加存储' },
    ]"
    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">
                <Database class="size-5" />
                存储配置
              </UiCardTitle>
              <UiCardDescription>填写存储的基本信息</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="grid gap-4 md:grid-cols-2">
                <div class="space-y-2">
                  <UiLabel for="name">
                    存储名称 <span class="text-destructive">*</span>
                  </UiLabel>
                  <UiInput
                    id="name"
                    v-model="formData.name"
                    placeholder="输入存储名称"
                    :disabled="saving"
                  />
                </div>

                <div class="space-y-2">
                  <UiLabel>存储类型 <span class="text-destructive">*</span></UiLabel>
                  <UiSelect v-model="formData.type" :disabled="saving">
                    <UiSelectTrigger>
                      <UiSelectValue placeholder="选择存储类型" />
                    </UiSelectTrigger>
                    <UiSelectContent>
                      <UiSelectItem v-for="type in storageTypes" :key="type.value" :value="type.value">
                        <div class="flex items-center gap-2">
                          <component :is="type.icon" class="h-4 w-4" />
                          {{ type.label }}
                        </div>
                      </UiSelectItem>
                    </UiSelectContent>
                  </UiSelect>
                </div>
              </div>

              <div v-if="!isLocal" class="space-y-4">
                <div class="space-y-2">
                  <UiLabel for="endpoint">端点/地址</UiLabel>
                  <UiInput
                    id="endpoint"
                    v-model="formData.endpoint"
                    :placeholder="endpointPlaceholder"
                    :disabled="saving"
                  />
                  <p class="text-xs text-muted-foreground">
                    {{ isS3 ? 'S3服务的端点地址' : '服务器地址和端口' }}
                  </p>
                </div>

                <div v-if="isS3" class="grid gap-4 md:grid-cols-2">
                  <div class="space-y-2">
                    <UiLabel for="bucket">存储桶 (Bucket)</UiLabel>
                    <UiInput
                      id="bucket"
                      v-model="formData.bucket"
                      placeholder="my-bucket"
                      :disabled="saving"
                    />
                  </div>
                  <div class="space-y-2">
                    <UiLabel for="region">区域 (Region)</UiLabel>
                    <UiInput
                      id="region"
                      v-model="formData.region"
                      placeholder="us-east-1"
                      :disabled="saving"
                    />
                  </div>
                </div>

                <div class="grid gap-4 md:grid-cols-2">
                  <div class="space-y-2">
                    <UiLabel for="access_key">
                      {{ isS3 ? 'Access Key' : '用户名' }}
                    </UiLabel>
                    <UiInput
                      id="access_key"
                      v-model="formData.access_key"
                      placeholder="请输入"
                      :disabled="saving"
                    />
                  </div>
                  <div class="space-y-2">
                    <UiLabel for="secret_key">
                      {{ isS3 ? 'Secret Key' : '密码' }}
                    </UiLabel>
                    <UiInput
                      id="secret_key"
                      v-model="formData.secret_key"
                      type="password"
                      placeholder="请输入"
                      :disabled="saving"
                    />
                  </div>
                </div>

                <div class="space-y-2">
                  <UiLabel for="path_prefix">路径前缀</UiLabel>
                  <UiInput
                    id="path_prefix"
                    v-model="formData.path_prefix"
                    placeholder="/uploads"
                    :disabled="saving"
                  />
                  <p class="text-xs text-muted-foreground">
                    文件存储的路径前缀，留空则存储在根目录
                  </p>
                </div>
              </div>

              <div class="space-y-2">
                <UiLabel for="remark">备注</UiLabel>
                <UiInput
                  id="remark"
                  v-model="formData.remark"
                  placeholder="备注信息（可选）"
                  :disabled="saving"
                />
              </div>

              <div class="flex items-center justify-between rounded-lg border p-4">
                <div class="space-y-0.5">
                  <UiLabel class="text-base">
                    设为默认存储
                  </UiLabel>
                  <p class="text-sm text-muted-foreground">
                    设为默认后，上传文件将优先使用此存储
                  </p>
                </div>
                <UiSwitch
                  v-model="formData.is_default"
                  :disabled="saving"
                />
              </div>

              <div class="flex items-center justify-between rounded-lg border p-4">
                <div class="space-y-0.5">
                  <UiLabel class="text-base">
                    启用状态
                  </UiLabel>
                  <p class="text-sm text-muted-foreground">
                    启用后该存储配置将可用
                  </p>
                </div>
                <UiSwitch
                  :checked="formData.status === 'active'"
                  :disabled="saving"
                  @update:checked="formData.status = $event ? 'active' : 'inactive'"
                />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                预览
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">存储名称</span>
                  <span class="truncate max-w-[120px]">{{ formData.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">存储类型</span>
                  <div class="flex items-center gap-1.5">
                    <component :is="selectedType?.icon || HardDrive" class="h-4 w-4" />
                    <span>{{ selectedType?.label || '-' }}</span>
                  </div>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">端点地址</span>
                  <span class="truncate max-w-[120px]">{{ formData.endpoint || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">默认存储</span>
                  <span>{{ formData.is_default ? '是' : '否' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">状态</span>
                  <span>{{ formData.status === 'active' ? '启用' : '禁用' }}</span>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardContent class="pt-6">
              <div class="flex flex-col gap-3">
                <UiButton
                  class="w-full"
                  size="lg"
                  :disabled="saving || !formData.name"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Plus v-else class="mr-2 h-4 w-4" />
                  添加存储
                </UiButton>
                <UiButton
                  v-if="!isLocal"
                  variant="outline"
                  class="w-full"
                  :disabled="testing"
                  @click="handleTest"
                >
                  <Loader2 v-if="testing" class="mr-2 h-4 w-4 animate-spin" />
                  <Plug v-else class="mr-2 h-4 w-4" />
                  测试连接
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  取消
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
