<template>
  <view class="page">
    <view class="nav-bar">
      <view class="nav-btn" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <text class="nav-title">草稿箱</text>
      <view class="nav-btn" />
    </view>

    <scroll-view scroll-y class="content" :scroll-top="scrollTop">
      <view v-if="drafts.length === 0 && !loading" class="empty">
        <text class="empty-icon">📝</text>
        <text class="empty-text">暂无草稿</text>
        <text class="empty-hint">在生成页面未保存的内容会自动保存到这里</text>
      </view>

      <view v-else class="draft-list">
        <view
          v-for="item in drafts"
          :key="item.id"
          class="draft-card"
          @click="restoreDraft(item)"
        >
          <view class="draft-header">
            <text class="draft-title">{{ item.title || '无标题' }}</text>
            <text class="draft-type">{{ getTypeLabel(item.type) }}</text>
          </view>
          <text class="draft-content">{{ item.content || '暂无内容' }}</text>
          <view class="draft-footer">
            <text class="draft-time">{{ formatTime(item.updatedAt) }}</text>
            <view class="draft-actions">
              <view class="action-btn delete" @click.stop="deleteDraft(item.id)">
                <text>删除</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { get, del } from '../../utils/request';

// scroll-top 用于避免 scrollTop 错误
const scrollTop = ref(0);

const drafts = ref<any[]>([]);
const loading = ref(false);

function goBack() {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/index/index' });
  }
}

function getTypeLabel(type: string): string {
  const labels: Record<string, string> = {
    audio: '音频',
    book: '书籍',
    chapter: '章节',
  };
  return labels[type] || type;
}

function formatTime(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return `${date.getMonth() + 1}/${date.getDate()}`;
}

async function fetchDrafts() {
  loading.value = true;
  try {
    const data = await get('/drafts');
    drafts.value = data || [];
  } catch (error) {
    console.error('获取草稿失败:', error);
  } finally {
    loading.value = false;
  }
}

function restoreDraft(item: any) {
  uni.showModal({
    title: '恢复草稿',
    content: '确定要恢复这个草稿吗？',
    success: (res) => {
      if (res.confirm) {
        uni.setStorageSync('draft', item);
        uni.showToast({ title: '已恢复，去生成页面查看', icon: 'success' });
        setTimeout(() => {
          uni.switchTab({ url: '/pages/create/index' });
        }, 1500);
      }
    },
  });
}

async function deleteDraft(id: number) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个草稿吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await del(`/drafts/${id}`);
          uni.showToast({ title: '删除成功', icon: 'success' });
          await fetchDrafts();
        } catch (error) {
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    },
  });
}

onMounted(() => {
  fetchDrafts();
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44rpx 32rpx 24rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 40rpx;
  color: #ffffff;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

.content {
  padding: 24rpx;
  height: calc(100vh - 160rpx);
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #6b7280;
  margin-bottom: 12rpx;
}

.empty-hint {
  font-size: 26rpx;
  color: #9ca3af;
  text-align: center;
  max-width: 500rpx;
}

.draft-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.draft-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.draft-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.draft-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.draft-type {
  padding: 4rpx 12rpx;
  background: #f3f4f6;
  color: #6b7280;
  font-size: 22rpx;
  border-radius: 8rpx;
  margin-left: 12rpx;
}

.draft-content {
  font-size: 26rpx;
  color: #6b7280;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 16rpx;
}

.draft-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.draft-time {
  font-size: 24rpx;
  color: #9ca3af;
}

.action-btn {
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.action-btn.delete {
  background: #fef2f2;
  color: #ef4444;
}

.loading {
  text-align: center;
  padding: 32rpx;
}

.loading text {
  font-size: 24rpx;
  color: #9ca3af;
}
</style>
