<template>
  <div v-if="visible" class="watchlist-panel">
    <div class="watchlist-header">
      <h3>待看名单</h3>
      <div class="header-actions">
        <span class="item-count-text">{{ itemCount }} 项</span>
        <button @click="exportWatchlist" class="export-btn" title="导出待看名单">
          <SvgIcon name="download" class="export-icon" />
        </button>
        <div class="import-section">
          <button @click="triggerImport" class="import-btn" title="导入待看名单">
            <SvgIcon name="upload" class="import-icon" />
          </button>
          <div class="import-mode-selector">
            <button 
              @click="importMode = 'merge'" 
              :class="['mode-btn', { active: importMode === 'merge' }]"
              title="重合模式：跳过已存在的项目"
            >
              重合
            </button>
            <button 
              @click="importMode = 'overwrite'" 
              :class="['mode-btn', { active: importMode === 'overwrite' }]"
              title="覆盖模式：删除所有现有项目后导入"
            >
              覆盖
            </button>
          </div>
        </div>
        <input
          ref="fileInput"
          type="file"
          accept=".json"
          style="display: none"
          @change="handleFileImport"
        />
        <button @click="$emit('showAddModal')" class="add-btn" title="手动添加">
          <SvgIcon name="add" class="add-icon" />
        </button>
        <button @click="$emit('close')" class="close-btn" title="关闭">
          <SvgIcon name="close" class="close-icon" />
        </button>
      </div>
    </div>

    <!-- 搜索和排序控制区域 -->
    <WatchlistControls :search-query="searchQuery" :sort-order="sortOrder"
      @update:search-query="$emit('update:searchQuery', $event)" @clear-search="$emit('clearSearch')"
      @toggle-sort="$emit('toggleSort')" />

    <!-- 存储模式设置 -->
    <div class="storage-config">
      <div class="storage-row">
        <span class="storage-label">存储模式：</span>
        <select v-model="selectedStorageMode" class="storage-select">
          <option value="json">JSON文件存储</option>
          <option value="database">MySQL数据库存储</option>
        </select>
        <span class="config-indicator" :class="{ unsaved: hasStorageModeChanges, saved: !hasStorageModeChanges }">
          <SvgIcon :name="hasStorageModeChanges ? 'warning' : 'check'" class="indicator-icon" />
          {{ hasStorageModeChanges ? '配置已修改' : `当前模式: ${storageModeText}` }}
        </span>
        <button class="save-config-btn" :disabled="configLoading || !hasStorageModeChanges" @click="saveStorageMode">
          保存
        </button>
        <button class="reset-config-btn" :disabled="configLoading || !hasStorageModeChanges" @click="resetStorageMode">
          重置
        </button>
      </div>
    </div>

    <!-- 内容区域 -->
    <WatchlistContent :loading="loading" :error="error" :items="items" :filtered-items="filteredItems"
      :search-query="searchQuery" :is-current-url="isCurrentUrl" :is-duplicate-author="isDuplicateAuthor"
      :is-pinned-current-artist="isPinnedCurrentArtist" @retry="$emit('retry')" @navigate="$emit('navigate', $event)"
      @edit="$emit('edit', $event)" @delete="$emit('delete', $event)" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useWatchlistStore } from '@/stores/watchlist';
import WatchlistControls from './WatchlistControls.vue';
import WatchlistContent from './WatchlistContent.vue';
import type { WatchlistItem } from '@/services/watchlist';

interface Props {
  visible: boolean;
  itemCount: number;
  loading: boolean;
  error: string | null;
  items: WatchlistItem[];
  filteredItems: WatchlistItem[];
  searchQuery: string;
  sortOrder: 'asc' | 'desc';
  isCurrentUrl: (url: string) => boolean;
  isDuplicateAuthor: (item: WatchlistItem) => boolean;
  isPinnedCurrentArtist: (item: WatchlistItem) => boolean;
}

defineProps<Props>();

defineEmits<{
  close: [];
  showAddModal: [];
  'update:searchQuery': [value: string];
  clearSearch: [];
  toggleSort: [];
  retry: [];
  navigate: [item: WatchlistItem];
  edit: [item: WatchlistItem];
  delete: [id: string];
}>();

// 获取watchlist store实例
const watchlistStore = useWatchlistStore();

// 导入模式状态
const importMode = ref<'merge' | 'overwrite'>('merge');

// 文件输入引用
const fileInput = ref<HTMLInputElement>();

// 导出功能
const exportWatchlist = () => {
  watchlistStore.exportWatchlist();
};

// 触发导入文件选择
const triggerImport = () => {
  fileInput.value?.click();
};

// 处理文件导入
const handleFileImport = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  
  if (!file) return;
  
  // 如果是覆盖模式，先确认
  if (importMode.value === 'overwrite') {
    const confirmed = confirm('覆盖模式将删除所有现有的待看项目，确定要继续吗？');
    if (!confirmed) {
      target.value = '';
      return;
    }
  }
  
  try {
    const result = await watchlistStore.importWatchlist(file, importMode.value);
    
    if (result.success) {
      alert(result.message);
    } else {
      alert(`导入失败: ${result.message}`);
    }
  } catch (error) {
    console.error('导入过程中发生错误:', error);
    alert('导入过程中发生错误，请检查文件格式');
  } finally {
    // 清空文件输入
    target.value = '';
  }
};

// 存储模式相关逻辑
const selectedStorageMode = ref<'json' | 'database'>('json');
const configLoading = computed(() => watchlistStore.configLoading);
const hasStorageModeChanges = computed(() => selectedStorageMode.value !== watchlistStore.storageMode);
const storageModeText = computed(() => watchlistStore.storageMode === 'database' ? 'MySQL数据库存储' : 'JSON文件存储');

const saveStorageMode = async () => {
  if (configLoading.value || !hasStorageModeChanges.value) return;
  const ok = await watchlistStore.saveStorageModeConfig(selectedStorageMode.value);
  if (!ok) return;
  // 成功后同步选择值并刷新列表与配置
  selectedStorageMode.value = watchlistStore.storageMode;
  await watchlistStore.fetchConfig();
  await watchlistStore.fetchItems();
};

const resetStorageMode = () => {
  selectedStorageMode.value = watchlistStore.storageMode;
};

onMounted(async () => {
  await watchlistStore.fetchConfig();
  selectedStorageMode.value = watchlistStore.storageMode;
});
</script>

<style scoped>
.watchlist-panel {
  position: absolute;
  top: 50px;
  left: 0;
  width: 570px;
  max-height: 600px;
  background: var(--color-bg-primary);
  border: 1px solid var(--color-border);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  z-index: 1002;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: panelSlideIn 0.3s ease-out;
}

@keyframes panelSlideIn {
  from {
    opacity: 0;
    transform: translateY(-10px) scale(0.95);
  }

  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.watchlist-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--color-border);
  background: var(--color-bg-secondary);
  border-radius: 12px 12px 0 0;
}

.watchlist-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
}

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

.storage-config {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  gap: 8px;
  border-bottom: 1px solid var(--color-border);
}

.storage-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.storage-label {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.storage-select {
  padding: 4px 8px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-bg-primary);
  color: var(--color-text-primary);
}

.config-indicator {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}
.config-indicator.saved {
  color: var(--color-success, #16a34a);
}
.config-indicator.unsaved {
  color: var(--color-warning, #ca8a04);
}
.indicator-icon {
  width: 14px;
  height: 14px;
}

.save-config-btn,
.reset-config-btn {
  padding: 6px 10px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  background: var(--color-bg-secondary);
  color: var(--color-text-primary);
  cursor: pointer;
}
.save-config-btn:disabled,
.reset-config-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.item-count-text {
  font-size: 12px;
  color: var(--color-text-secondary);
  font-weight: 500;
}

.add-btn,
.close-btn,
.export-btn,
.import-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.add-btn:hover {
  background: var(--color-primary-light);
  color: var(--color-primary);
}

.export-btn:hover {
  background: var(--color-success-light);
  color: var(--color-success);
}

.import-btn:hover {
  background: var(--color-info-light);
  color: var(--color-info);
}

.close-btn:hover {
  background: var(--color-danger-light);
  color: var(--color-danger);
}

.add-icon,
.close-icon,
.export-icon,
.import-icon {
  width: 14px;
  height: 14px;
}

/* 导入区域样式 */
.import-section {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.import-mode-selector {
  display: flex;
  background: var(--color-bg-tertiary);
  border-radius: 4px;
  padding: 2px;
  gap: 2px;
}

.mode-btn {
  padding: 4px 8px;
  font-size: 11px;
  border: none;
  border-radius: 3px;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.mode-btn:hover {
  background: var(--color-bg-hover);
  color: var(--color-text-primary);
}

.mode-btn.active {
  background: var(--color-primary);
  color: white;
  font-weight: 500;
}

.mode-btn.active:hover {
  background: var(--color-primary-dark);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .watchlist-panel {
    position: fixed;
    /* 向下偏移导航栏高度，避免与顶部导航重叠 */
    top: 3.5rem;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    max-height: 100vh;
    border-radius: 0;
    animation: panelSlideUp 0.3s ease-out;
  }

  @keyframes panelSlideUp {
    from {
      opacity: 0;
      transform: translateY(100%);
    }

    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .watchlist-header {
    border-radius: 0;
    /* 让标题和操作区在小屏下更好适配 */
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  /* 标题可收缩，给右侧操作区更多空间 */
  .watchlist-header h3 {
    flex: 1;
    min-width: 0;
  }

  /* 移动端隐藏容易占空间的元素，避免溢出 */
  .item-count-text,
  .import-mode-selector {
    display: none;
  }

  /* 压缩按钮尺寸与间距，保证关闭按钮可见 */
  .header-actions {
    gap: 8px;
    flex-wrap: nowrap;
  }

  .add-btn,
  .close-btn,
  .export-btn,
  .import-btn {
    width: 26px;
    height: 26px;
  }
}

@media (max-width: 480px) {
  .watchlist-header {
    padding: 12px 16px;
  }

  .watchlist-header h3 {
    font-size: 14px;
  }

  .item-count-text {
    font-size: 11px;
  }
}
</style>