<template>
  <!-- 快速上传隐藏输入（始终可用，独立于对话框） -->
  <input 
    ref="quickInputRef"
    type="file" 
    style="display: none" 
    @change="onQuickFileSelect"
  />
  <n-modal
    v-model:show="showModal"
    preset="card"
    :title="t('Add Files')"
    :style="{ width: '600px' }"
    :bordered="false"
    size="huge"
    :segmented="{ content: true, footer: true }"
  >
    <div class="upload-dialog">
      <!-- 上传方式选择 -->
      <div v-if="!activeTab" class="upload-methods">
        
        <div class="method-grid">
          <!-- 单文件即时上传 -->
          <div class="method-card" @click="handleDeviceClick">
            <div class="method-icon">
              <Icon icon="tabler:file" :size="32" />
            </div>
            <div class="method-label">{{ t('My Device') }}</div>
            <div class="method-desc">{{ t('Select a file to upload instantly') }}</div>
          </div>
          
          <!-- 网页链接 -->
          <div class="method-card" @click="switchTab('link')">
            <div class="method-icon">
              <Icon icon="tabler:link" :size="32" />
            </div>
            <div class="method-label">{{ t('Link') }}</div>
            <div class="method-desc">{{ t('Add file from URL') }}</div>
          </div>
          
          <!-- Google Drive -->
          <div v-if="googleDriveEnabled" class="method-card" @click="handleGoogleDrive">
            <div class="method-icon">
              <svg width="32" height="32" viewBox="0 0 32 32">
                <path fill="#4285F4" d="M16.7 14.2l2.5-2.5H27v15.8H5V6.2h10.5l-2.5-2.5-6.7 6.7 6.7 6.8z"/>
                <path fill="#34A853" d="M16.7 17.8l2.5 2.5h7.8V3.2H5v15.8h10.5l-2.5 2.5 6.7 6.8 6.7-6.8-5.7-5.7z"/>
                <path fill="#FBBC05" d="M16.7 6.7L9.5 13.8l2.5 2.5 4.7-4.7v6.7h3.3V11.6l4.7 4.7 2.5-2.5L16.7 6.7z"/>
              </svg>
            </div>
            <div class="method-label">{{ t('Google Drive') }}</div>
            <div class="method-desc">{{ t('Import from Google Drive') }}</div>
          </div>
        </div>
        
        <!-- 多文件批量上传拖拽区 -->
        <div 
          class="drop-zone"
          :class="{ 'drag-over': isDragging }"
          @click="fileInputRef?.click()"
        >
          <Icon icon="tabler:files" :size="48" />
          <div class="drop-text">{{ t('Drag and drop files here. Click to select multiple files') }}</div>
          <input 
            ref="fileInputRef"
            type="file" 
            multiple 
            style="display: none" 
            @change="onFileSelect"
          />
        </div>
      </div>
      
      <!-- 本地上传 -->
      <div v-if="activeTab === 'device'" class="device-upload">
        <div class="tab-header">
          <n-button text @click="switchTab('')">
            <Icon icon="tabler:arrow-left" :size="18" />
            {{ t('Back') }}
          </n-button>
          <span class="tab-title">{{ t('Upload from Device') }}</span>
        </div>
        
        <!-- 文件列表 -->
        <div class="file-list" v-if="uploadQueue.length > 0">
          <div 
            v-for="(item, index) in uploadQueue" 
            :key="item.id"
            class="file-item"
            :class="`status-${item.status}`"
          >
            <div class="file-info">
              <!-- 状态图标 -->
              <div class="status-icon">
                <n-spin v-if="item.status === 'uploading'" :size="16" />
                <Icon v-else-if="item.status === 'success'" icon="tabler:check" :size="18" class="icon-success" />
                <Icon v-else-if="item.status === 'error'" icon="tabler:x" :size="18" class="icon-error" />
                <Icon v-else :icon="getFileIcon(item.name)" :size="20" />
              </div>
              <span class="file-name">{{ item.name }}</span>
              <span class="file-size">({{ formatFileSize(item.size) }})</span>
            </div>
            
            <!-- 操作按钮 -->
            <div class="file-actions">
              <!-- 失败时显示重试 -->
              <n-button 
                v-if="item.status === 'error'" 
                text 
                size="tiny"
                @click="retryFile(index)"
              >
                {{ t('Retry') }}
              </n-button>
              <!-- 移除按钮（仅上传前可移除） -->
              <button 
                v-if="item.status === 'pending'" 
                class="remove-btn" 
                @click="removeFile(index)"
              >
                <Icon icon="tabler:x" :size="16" />
              </button>
            </div>
          </div>
        </div>
        
        <!-- 添加更多文件 -->
        <div class="upload-area" @click="fileInputRef?.click()">
          <Icon icon="tabler:plus" :size="32" />
          <div>{{ t('Add More Files') }}</div>
          <input 
            ref="fileInputRef"
            type="file" 
            multiple 
            style="display: none" 
            @change="onFileSelect"
          />
        </div>
        
        <!-- 底部操作栏 -->
        <div class="upload-actions">
          <n-button @click="closeDialog">{{ t('Close') }}</n-button>
          <n-button 
            type="primary" 
            :disabled="!hasPendingFiles || isUploading"
            :loading="isUploading"
            @click="startUpload"
          >
            {{ t('Upload') }} ({{ pendingCount }})
          </n-button>
        </div>
      </div>
      
      <!-- 链接上传 -->
      <div v-if="activeTab === 'link'" class="link-upload">
        <div class="tab-header">
          <n-button text @click="switchTab('')">
            <Icon icon="tabler:arrow-left" :size="18" />
            {{ t('Back') }}
          </n-button>
        </div>
        
        <div class="link-form">
          <n-input
            v-model:value="linkUrl"
            :placeholder="t('Enter file URL')"
            size="large"
          />
        </div>
        
        <div class="upload-actions">
          <n-button @click="switchTab('')">{{ t('Cancel') }}</n-button>
          <n-button 
            type="primary" 
            :disabled="!linkUrl"
            :loading="linkUploading"
            @click="uploadFromLink"
          >
            {{ t('Add') }}
          </n-button>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { NModal, NButton, NInput, NSpin, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { uploadFileToJingrow } from '@/shared/api/common'
import { api } from '@/shared/api/common'

const props = defineProps<{
  show: boolean
  pagetype?: string
  pagename?: string
  pagefield?: string
  folder?: string
}>()

const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
  (e: 'uploaded'): void
}>()

const message = useMessage()

const showModal = computed({
  get: () => props.show,
  set: (value) => emit('update:show', value)
})

// 文件上传项接口
interface UploadItem {
  id: number
  name: string
  size: number
  file: File
  status: 'pending' | 'uploading' | 'success' | 'error'
}

let fileIdCounter = 0

const activeTab = ref('')
const fileInputRef = ref<HTMLInputElement | null>(null)
const quickInputRef = ref<HTMLInputElement | null>(null)
const uploadQueue = ref<UploadItem[]>([])
const isDragging = ref(false)
const isUploading = computed(() => uploadQueue.value.some(f => f.status === 'uploading'))

// Google Drive
const googleDriveEnabled = ref(false)

// Link state
const linkUrl = ref('')
const linkUploading = ref(false)

// Computed
const hasPendingFiles = computed(() => uploadQueue.value.some(f => f.status === 'pending'))
const pendingCount = computed(() => uploadQueue.value.filter(f => f.status === 'pending').length)

// Track last drop time to prevent duplicate drops
let lastDropTime = 0

function switchTab(tab: string) {
  activeTab.value = tab
}

function getFileIcon(filename: string): string {
  const ext = filename.split('.').pop()?.toLowerCase()
  const iconMap: Record<string, string> = {
    pdf: 'tabler:file-type-pdf',
    doc: 'tabler:file-type-doc',
    docx: 'tabler:file-type-doc',
    xls: 'tabler:file-type-xls',
    xlsx: 'tabler:file-type-xls',
    ppt: 'tabler:file-type-ppt',
    pptx: 'tabler:file-type-ppt',
    zip: 'tabler:file-zip',
    rar: 'tabler:file-zip',
    txt: 'tabler:file-text',
    jpg: 'tabler:photo',
    jpeg: 'tabler:photo',
    png: 'tabler:photo',
    gif: 'tabler:photo',
    mp4: 'tabler:video',
    mp3: 'tabler:music',
  }
  return iconMap[ext || ''] || 'tabler:file'
}

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 parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

// Global drag handlers
function onGlobalDragOver(e: DragEvent) {
  e.preventDefault()
  if (e.dataTransfer?.types.includes('Files')) {
    isDragging.value = true
  }
}

function onGlobalDragLeave(e: DragEvent) {
  if (e.relatedTarget === null || 
      (e.relatedTarget as Node)?.nodeType === Node.DOCUMENT_NODE) {
    isDragging.value = false
  }
}

function onGlobalDrop(e: DragEvent) {
  e.preventDefault()
  e.stopPropagation()
  
  const now = Date.now()
  if (now - lastDropTime < 100) {
    return
  }
  lastDropTime = now
  
  isDragging.value = false
  
  const files = e.dataTransfer?.files
  if (files && files.length > 0) {
    handleFiles(Array.from(files))
  }
}

function onFileSelect(e: Event) {
  const input = e.target as HTMLInputElement
  if (input.files) {
    handleFiles(Array.from(input.files))
    input.value = ''
  }
}

// Single file auto-upload — dialog already closed, just notify result
async function handleSingleUpload(file: File) {
  try {
    const result = await uploadFileToJingrow(
      file,
      props.pagetype || '',
      props.pagename || '',
      props.pagefield || '',
      props.folder || ''
    )
    if (result.success) {
      emit('uploaded')
      message.success(t('Upload successful'))
    } else {
      message.error(t('Upload failed'))
    }
  } catch {
    message.error(t('Upload failed'))
  }
}

// My Device: close dialog first, then open single-file picker
async function handleDeviceClick() {
  showModal.value = false
  await nextTick()
  quickInputRef.value?.click()
}

// Handle multi-file selection → queue
function handleFiles(files: File[]) {
  const newItems: UploadItem[] = files.map(file => ({
    id: ++fileIdCounter,
    name: file.name,
    size: file.size,
    file,
    status: 'pending'
  }))
  uploadQueue.value.push(...newItems)
  activeTab.value = 'device'
}

function removeFile(index: number) {
  uploadQueue.value.splice(index, 1)
}

function retryFile(index: number) {
  const item = uploadQueue.value[index]
  if (item) {
    item.status = 'pending'
  }
}

async function startUpload() {
  const pendingItems = uploadQueue.value.filter(f => f.status === 'pending')
  
  // 并行上传所有待处理文件
  const uploadPromises = pendingItems.map(async (item) => {
    item.status = 'uploading'
    try {
      const result = await uploadFileToJingrow(
        item.file, 
        props.pagetype || '', 
        props.pagename || '', 
        props.pagefield || ''
      )
      item.status = result.success ? 'success' : 'error'
    } catch {
      item.status = 'error'
    }
  })
  
  await Promise.all(uploadPromises)
  
  // 通知父组件
  const successCount = uploadQueue.value.filter(f => f.status === 'success').length
  if (successCount > 0) {
    emit('uploaded')
    message.success(t('{count} files uploaded successfully', { count: successCount }))
  }
}

async function uploadFromLink() {
  if (!linkUrl.value) return
  
  linkUploading.value = true
  try {
    const result = await api.call('upload_file', {
      file_url: linkUrl.value,
      folder: props.folder || 'Home'
    })
    
    if (result.message) {
      message.success(t('Link added successfully'))
      emit('uploaded')
      linkUrl.value = ''
      showModal.value = false
    } else {
      message.error(t('Failed to add link'))
    }
  } catch {
    message.error(t('Failed to add link'))
  } finally {
    linkUploading.value = false
  }
}

function closeDialog() {
  // 清空已完成和失败的文件，保留上传成功的
  uploadQueue.value = uploadQueue.value.filter(f => f.status === 'uploading')
  showModal.value = false
}

function handleGoogleDrive() {
  message.info(t('Google Drive integration coming soon'))
}

function quickUpload() {
  quickInputRef.value?.click()
}

function onQuickFileSelect(e: Event) {
  const input = e.target as HTMLInputElement
  if (input.files && input.files[0]) {
    handleSingleUpload(input.files[0])
    input.value = ''
  }
}

defineExpose({ quickUpload })

onMounted(() => {
  document.addEventListener('dragover', onGlobalDragOver)
  document.addEventListener('dragleave', onGlobalDragLeave)
  document.addEventListener('drop', onGlobalDrop)
})

onUnmounted(() => {
  document.removeEventListener('dragover', onGlobalDragOver)
  document.removeEventListener('dragleave', onGlobalDragLeave)
  document.removeEventListener('drop', onGlobalDrop)
})
</script>

<style scoped>
.upload-dialog {
  min-height: 400px;
}

.upload-methods {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.upload-hint {
  text-align: center;
  color: #64748b;
  font-size: 14px;
}

.method-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 16px;
}

.method-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.method-card:hover {
  border-color: #1fc76f;
  background: #f0fdf4;
  transform: translateY(-2px);
}

.method-icon {
  color: #64748b;
}

.method-card:hover .method-icon {
  color: #1fc76f;
}

.method-label {
  font-weight: 600;
  color: #374151;
}

.method-desc {
  font-size: 12px;
  color: #9ca3af;
}

.drop-zone {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 32px;
  border: 2px dashed #e2e8f0;
  border-radius: 12px;
  color: #9ca3af;
  cursor: pointer;
  transition: all 0.2s;
}

.drop-zone:hover,
.drop-zone.drag-over {
  border-color: #1fc76f;
  background: #f0fdf4;
  color: #1fc76f;
}

.drop-text {
  font-size: 14px;
}

/* Tab views */
.tab-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.tab-title {
  font-weight: 600;
  font-size: 16px;
  color: #1f2937;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
  max-height: 280px;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: #f8fafc;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.file-item.status-success {
  background: #f0fdf4;
}

.file-item.status-error {
  background: #fef2f2;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
}

.status-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-success {
  color: #22c55e;
}

.icon-error {
  color: #ef4444;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.file-size {
  color: #9ca3af;
  font-size: 12px;
}

.file-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.remove-btn {
  background: none;
  border: none;
  color: #9ca3af;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  transition: all 0.2s;
}

.remove-btn:hover {
  background: #fee2e2;
  color: #ef4444;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 24px;
  border: 1px dashed #e2e8f0;
  border-radius: 8px;
  color: #9ca3af;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-area:hover {
  border-color: #1fc76f;
  color: #1fc76f;
}

.upload-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e2e8f0;
}

/* Link */
.link-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
</style>
