<template>
  <div class="app-detail">
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h1>{{ t('Publish App') }}</h1>
        </div>
        <div class="header-actions">
          <n-button @click="goBack" size="medium">
            <template #icon>
              <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
            </template>
            {{ t('Back') }}
          </n-button>
          <n-button type="primary" @click="handlePublishApp" :loading="publishing" size="medium">
            <template #icon>
              <n-icon><Icon icon="tabler:upload" /></n-icon>
            </template>
            {{ t('Publish') }}
          </n-button>
        </div>
      </div>
    </div>

    <div class="app-content">
      <!-- 整体卡片布局 -->
      <div class="app-card">
        <!-- 上部分：应用信息 -->
        <div class="app-info-section">
          <div class="app-content-layout">
            <!-- 左侧：应用图片 -->
            <div class="app-image-section">
              <div 
                class="app-image"
                @dragover.prevent="handleDragOver"
                @dragenter.prevent="handleDragEnter"
                @dragleave.prevent="handleDragLeave"
                @drop.prevent="handleImageDrop"
                @click="handleImageClick"
                :class="{ 'drag-over': isDragOver }"
              >
                <img 
                  v-if="imagePreview" 
                  :src="imagePreview" 
                  alt="应用图片预览"
                />
                <div v-if="imagePreview" class="image-actions">
                  <n-button 
                    type="error" 
                    size="small" 
                    circle
                    @click.stop="removeImage"
                    class="remove-btn"
                  >
                    <template #icon>
                      <n-icon><Icon icon="tabler:x" /></n-icon>
                    </template>
                  </n-button>
                </div>
                <div v-else class="placeholder-image">
                  <n-icon size="80"><Icon icon="tabler:apps" /></n-icon>
                  <p class="upload-hint">{{ t('Click or drag to upload image') }}</p>
                </div>
                <div v-if="isDragOver" class="drag-overlay">
                  <n-icon size="60"><Icon icon="tabler:upload" /></n-icon>
                  <p>{{ t('Drop image here') }}</p>
                </div>
              </div>
              
              <!-- 隐藏的文件输入 -->
              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                style="display: none"
                @change="handleFileSelect"
              />
            </div>
            
            <!-- 右侧：应用信息 -->
            <div class="app-info-content">
              <div class="app-header">
              </div>
              
              <div class="info-list">
                <div class="info-item">
                  <span class="label">{{ t('App Title') }}:<span class="required">*</span></span>
                  <n-input v-model:value="form.title" :placeholder="t('App title')" />
                </div>
 
                <div class="info-item">
                  <span class="label">{{ t('App Name') }}:<span class="required">*</span></span>
                  <n-input v-model:value="form.app_name" :placeholder="t('App name')" />
                </div>
                
                <div class="info-item">
                  <span class="label">{{ t('Subtitle') }}:</span>
                  <n-input 
                    v-model:value="form.subtitle" 
                    type="textarea" 
                    :placeholder="t('Brief description')"
                    :rows="3"
                  />
                </div>
                

                
                <div class="info-item">
                  <span class="label">{{ t('Repository URL') }}:</span>
                  <n-input v-model:value="form.repository_url" :placeholder="t('Repository URL')" />
                </div>
                
                <div class="info-item">
                  <span class="label">{{ t('File URL') }}:</span>
                  <n-input v-model:value="form.file_url" :placeholder="t('File URL')" />
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 下部分：描述 -->
        <div class="app-description-section">
          <div class="description-content">
            <Jeditor
              :df="{ fieldname: 'description', label: t('Description'), fieldtype: 'Jeditor' }"
              v-model="form.description"
              :ctx="{ t }"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NInput, NIcon, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import axios from 'axios'
import Jeditor from '@/core/pagetype/form/controls/Jeditor.vue'

const router = useRouter()
const message = useMessage()

const publishing = ref(false)
const imagePreview = ref('')
const uploadedImageUrl = ref('')
const isDragOver = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)

const form = ref({
  title: '',
  app_name: '',
  subtitle: '',
  repository_url: '',
  file_url: '',
  description: ''
})

const goBack = () => {
  router.push('/app-marketplace')
}

const handleImageDrop = async (event: DragEvent) => {
  isDragOver.value = false
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    const file = files[0]
    if (file.type.startsWith('image/')) {
      await handleImageUpload({ file: { file } })
    } else {
      message.error('请选择图片文件')
    }
  }
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDragEnter = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  // 只有当离开整个拖拽区域时才设置为 false
  const currentTarget = event.currentTarget as HTMLElement
  const relatedTarget = event.relatedTarget as Node | null
  if (!currentTarget.contains(relatedTarget)) {
    isDragOver.value = false
  }
}

const handleImageClick = () => {
  fileInput.value?.click()
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    await handleImageUpload({ file: { file } })
  }
}

const removeImage = () => {
  imagePreview.value = ''
  uploadedImageUrl.value = ''
  // 清空文件输入
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const handleImageUpload = async (options: any) => {
  const { file, onFinish, onError } = options.file?.file ? 
    { file: options.file.file, onFinish: options.onFinish, onError: options.onError } :
    options.fileList?.length ? 
    { file: options.fileList[0].file, onFinish: options.onFinish, onError: options.onError } :
    options instanceof File ? 
    { file: options, onFinish: null, onError: null } :
    { file: null, onFinish: null, onError: null }
  
  if (!file || !(file instanceof File)) {
    if (onError) onError(new Error('无效的文件'))
    return
  }

  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file)

  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await axios.post('/jingrow/upload-image', formData, { timeout: 30000 })
    
    if (response.data.success) {
      uploadedImageUrl.value = response.data.url
      message.success('图片上传成功')
      if (onFinish) onFinish()
    } else {
      const errorMsg = response.data.error || '图片上传失败'
      message.error(errorMsg)
      if (onError) onError(new Error(errorMsg))
    }
  } catch (error: any) {
    const errorMsg = error.response?.data?.detail || error.message || '图片上传失败'
    message.error('图片上传失败: ' + errorMsg)
    if (onError) onError(new Error(errorMsg))
  }
}

const handlePublishApp = async () => {
  if (!form.value.title || !form.value.app_name) {
    message.error('请填写应用标题和应用名称')
    return
  }

  publishing.value = true
  
  try {
    const formData = new FormData()
    Object.entries(form.value).forEach(([key, value]) => {
      if (value) formData.append(key, value)
    })
    
    if (uploadedImageUrl.value) {
      formData.append('app_image', uploadedImageUrl.value)
    }
    
    const response = await axios.post('/jingrow/create-app', formData)
    
    if (response.data.success) {
      message.success('应用发布成功')
      router.push('/app-marketplace')
    } else {
      message.error('应用发布失败')
    }
  } catch (error: any) {
    message.error(error.response?.data?.detail || '应用发布失败')
  } finally {
    publishing.value = false
  }
}
</script>

<style scoped>
.app-detail {
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 30px;
}

.header-text h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  color: #1a1a1a;
}

.header-text p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.app-content {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

/* 整体卡片布局 */
.app-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 上部分：应用信息 */
.app-content-layout {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 24px;
}

.app-image-section {
  display: flex;
  justify-content: center;
  align-items: center;
}

.app-image {
  width: 100%;
  min-width: 300px;
  min-height: 300px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border: 2px dashed #d1d5db;
  transition: all 0.3s ease;
  cursor: pointer;
}

.app-image:hover {
  border-color: #3b82f6;
  background-color: #f8fafc;
}

.app-image.drag-over {
  border-color: #10b981;
  background-color: #f0fdf4;
  border-style: solid;
}

.drag-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(16, 185, 129, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #10b981;
  font-weight: 500;
  z-index: 10;
}

.drag-overlay p {
  margin: 8px 0 0 0;
  font-size: 14px;
}

.app-image img {
  width: 100%;
  height: auto;
  object-fit: contain;
}

.placeholder-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
}

.upload-hint {
  margin: 12px 0 0 0;
  font-size: 14px;
  color: #6b7280;
  text-align: center;
}

.image-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
}

.remove-btn {
  width: 24px;
  height: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  background: rgba(239, 68, 68, 0.9);
  border: none;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: #ef4444;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

.remove-btn .n-icon {
  font-size: 14px;
}

.image-upload-overlay {
  position: absolute;
  bottom: 8px;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

.app-image:hover .image-upload-overlay {
  opacity: 1;
}

.app-info-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.app-header {
  margin-bottom: 8px;
}

.app-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-item .label {
  font-weight: 500;
  color: #374151;
  min-width: 100px;
  flex-shrink: 0;
}

.info-item .value {
  color: #6b7280;
}

.info-item .n-input {
  flex: 1;
}

.required {
  color: #ef4444;
  font-weight: bold;
  margin-left: 2px;
}

/* 下部分：描述 */
.app-description-section {
  border-top: 1px solid #e5e7eb;
  padding-top: 24px;
}

.app-description-section h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.app-subtitle {
  margin: 8px 0 0 0;
}

.description-content {
  color: #6b7280;
  line-height: 1.6;
}

/* Jeditor 样式调整 */
.description-content .field-wrapper {
  margin: 0;
}

.description-content .field-label {
  display: none; /* 隐藏标签，因为已经有 h3 标题了 */
}

.description-content .jeditor-control {
  margin-top: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

@media (max-width: 768px) {
  .app-detail {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .app-content-layout {
    grid-template-columns: 1fr;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
}
</style>