<template>
  <div
    class="drop-zone"
    :class="{
      'is-dragging': isDragging,
      'is-disabled': disabled,
      'has-files': selectedFiles.length > 0
    }"
    @dragenter.prevent="onDragEnter"
    @dragover.prevent="onDragOver"
    @dragleave.prevent="onDragLeave"
    @drop.prevent="onDrop"
    @click="handleClick"
  >
    <input
      ref="fileInput"
      type="file"
      :accept="acceptedTypes"
      :multiple="multiple"
      :disabled="disabled"
      class="file-input"
      @change="onFileChange"
    />

    <div v-if="!disabled" class="drop-zone-content">
      <template v-if="!isDragging">
        <InboxOutlined class="drop-icon" :style="{ fontSize: iconSize + 'px' }" />
        <p class="drop-text">
          拖拽文件到此处，或<span class="link">点击选择</span>
        </p>
        <p class="drop-hint">{{ acceptedTypesHint }}，最大 {{ formatFileSize(maxSize) }}</p>
      </template>

      <template v-else>
        <CloudUploadOutlined class="drop-icon drag-icon" />
        <p class="drop-text drag-text">释放文件以上传</p>
      </template>
    </div>

    <div v-else class="drop-zone-content disabled-content">
      <StopOutlined class="drop-icon disabled-icon" />
      <p class="drop-text">上传功能已禁用</p>
    </div>

    <div v-if="selectedFiles.length > 0" class="file-preview">
      <div class="preview-header">
        <CheckCircleOutlined class="preview-icon" />
        <span>已选择 {{ selectedFiles.length }} 个文件</span>
        <button class="clear-btn" @click.stop="clearFiles">清除</button>
      </div>

      <div class="preview-list">
        <div
          v-for="(file, index) in previewFiles"
          :key="index"
          class="preview-item"
        >
          <FileTextOutlined class="item-icon" />
          <span class="item-name" :title="file.name">{{ file.name }}</span>
          <span class="item-size">{{ formatFileSize(file.size) }}</span>
        </div>
        <p v-if="selectedFiles.length > maxPreviewCount" class="more-hint">
          还有 {{ selectedFiles.length - maxPreviewCount }} 个文件...
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import {
  InboxOutlined,
  CloudUploadOutlined,
  StopOutlined,
  CheckCircleOutlined,
  FileTextOutlined
} from '@ant-design/icons-vue'
import { validateFiles, formatFileSize } from '../../utils/fileValidator.js'

const props = defineProps({
  acceptedTypes: {
    type: String,
    default: '.docx,.pdf,.txt,.md,.xlsx,.pptx'
  },
  maxSize: {
    type: Number,
    default: 50 * 1024 * 1024
  },
  multiple: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  iconSize: {
    type: Number,
    default: 48
  },
  maxPreviewCount: {
    type: Number,
    default: 3
  }
})

const emit = defineEmits(['files-selected', 'error', 'clear'])

const fileInput = ref(null)
const isDragging = ref(false)
const selectedFiles = ref([])

const acceptedTypesHint = computed(() => {
  return props.acceptedTypes
    .split(',')
    .map(type => type.trim().replace('.', ''))
    .join(' ')
})

const previewFiles = computed(() => {
  return selectedFiles.value.slice(0, props.maxPreviewCount)
})

function onDragEnter(e) {
  if (props.disabled) return
  isDragging.value = true
}

function onDragOver(e) {
  if (props.disabled) return
  e.dataTransfer.dropEffect = 'copy'
}

function onDragLeave(e) {
  if (props.disabled) return
  const relatedTarget = e.relatedTarget
  if (!relatedTarget || !e.currentTarget.contains(relatedTarget)) {
    isDragging.value = false
  }
}

function onDrop(e) {
  if (props.disabled) return
  isDragging.value = false

  const files = e.dataTransfer.files
  processFiles(files)
}

function handleClick() {
  if (props.disabled) return

  if (!props.multiple && selectedFiles.value.length > 0) {
    clearFiles()
  }

  fileInput.value?.click()
}

function onFileChange(e) {
  const files = e.target.files
  processFiles(files)

  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

function processFiles(fileList) {
  if (!fileList || fileList.length === 0) return

  const filesArray = Array.from(fileList)
  const filesToProcess = props.multiple ? filesArray : [filesArray[0]]

  const { validFiles, invalidFiles } = validateFiles(filesToProcess)

  if (validFiles.length > 0) {
    selectedFiles.value = props.multiple
      ? [...selectedFiles.value, ...validFiles]
      : validFiles
    emit('files-selected', validFiles)
  }

  if (invalidFiles.length > 0) {
    emit('error', invalidFiles)
  }
}

function clearFiles() {
  selectedFiles.value = []
  emit('clear')
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

defineExpose({ clearFiles })
</script>

<style scoped>
.drop-zone {
  position: relative;
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  padding: 32px 24px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  text-align: center;
}

.drop-zone:hover:not(.is-disabled):not(.is-dragging) {
  border-color: #9ca3af;
  background: #f5f5f5;
}

.drop-zone.is-dragging {
  border: 3px dashed #3b82f6;
  background: #eff6ff;
  transform: scale(1.01);
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
  animation: border-pulse 1s ease-in-out infinite;
}

.drop-zone.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f9fafb;
  pointer-events: none;
}

.drop-zone.has-files {
  padding-bottom: 16px;
}

.file-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
  overflow: hidden;
}

.drop-zone-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.drop-icon {
  color: #9ca3af;
  margin-bottom: 4px;
}

.drop-text {
  font-size: 14px;
  color: #374151;
  margin: 0;
  line-height: 1.5;
}

.drop-text .link {
  color: #3b82f6;
  text-decoration: underline;
  cursor: pointer;
  font-weight: 500;
}

.drop-hint {
  font-size: 12px;
  color: #9ca3af;
  margin: 0;
}

.drag-icon {
  color: #3b82f6;
  font-size: 48px !important;
}

.drag-text {
  font-size: 16px;
  font-weight: 600;
  color: #3b82f6;
}

.disabled-icon {
  color: #9ca3af;
}

.disabled-content .drop-text {
  color: #9ca3af;
}

.file-preview {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
  text-align: left;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #374151;
}

.preview-icon {
  color: #10b981;
  font-size: 16px;
}

.clear-btn {
  margin-left: auto;
  background: none;
  border: none;
  color: #ef4444;
  cursor: pointer;
  font-size: 13px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.clear-btn:hover {
  background: #fef2f2;
}

.preview-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 10px;
  background: #f9fafb;
  border-radius: 6px;
  font-size: 13px;
}

.item-icon {
  color: #9ca3af;
  font-size: 16px;
  flex-shrink: 0;
}

.item-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #374151;
}

.item-size {
  color: #9ca3af;
  font-size: 12px;
  flex-shrink: 0;
}

.more-hint {
  font-size: 12px;
  font-style: italic;
  color: #9ca3af;
  margin: 8px 0 0 0;
  text-align: center;
}

@keyframes border-pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@media (max-width: 640px) {
  .drop-zone {
    padding: 24px 16px;
  }

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

  .drop-hint {
    font-size: 11px;
  }

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

  .preview-item {
    padding: 6px 8px;
    font-size: 12px;
  }
}
</style>
