<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="page-title">AI 生成内容</text>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 主题输入卡片 -->
      <view class="card topic-card">
        <view class="card-header">
          <text class="card-title">📝 输入主题</text>
        </view>
        <textarea
          v-model="topic"
          class="topic-input"
          placeholder="请输入你想要生成的内容主题或具体要求，例如：'人工智能对未来工作的影响'、'请写一篇关于阅读的散文，1000字左右'..."
        />
        <view class="word-count">
          <text>{{ topic.length }} 字</text>
        </view>
      </view>

      <!-- 生成按钮 -->
      <button
        class="generate-btn"
        :disabled="!canGenerate || generating"
        @click="handleGenerate"
      >
        {{ generating ? '🤖 AI 生成中...' : '🚀 开始生成' }}
      </button>

      <!-- 生成结果 -->
      <view v-if="generatedContent" class="card result-card">
        <view class="card-header-row">
          <text class="card-title">✨ 生成结果</text>
          <text class="word-count-badge">{{ wordCount }} 字</text>
        </view>
        <view class="result-content">
          <text>{{ generatedContent }}</text>
        </view>
        <view class="result-actions">
          <button class="action-btn primary" @click="useContent">
            <text>✓ 使用此内容</text>
          </button>
          <button class="action-btn" @click="copyContent">
            <text>📋 复制</text>
          </button>
          <button class="action-btn" @click="regenerate">
            <text>🔄 重新生成</text>
          </button>
        </view>
      </view>

      <!-- 生成中提示 -->
      <view v-if="generating && !generatedContent" class="generating-tip">
        <view class="loading-spinner"></view>
        <text class="tip-text">AI 正在努力创作中...</text>
      </view>
    </view>
  </view>
</template>

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

const topic = ref('');
const generating = ref(false);
const generatedContent = ref('');
const wordCount = computed(() => {
  const text = generatedContent.value.replace(/\s/g, '');
  return (text.match(/[\u4e00-\u9fa5]/g) || []).length;
});

const canGenerate = computed(() => {
  return topic.value.trim().length > 0 && !generating.value;
});

async function handleGenerate() {
  if (!canGenerate.value) return;

  generating.value = true;
  generatedContent.value = '';

  try {
    const result = await post<{ content: string; wordCount: number }>(
      '/book-generator/ai-generate/sync',
      {
        topic: topic.value.trim(),
      }
    );

    if (result.content) {
      generatedContent.value = result.content;
      uni.showToast({ title: '生成成功！', icon: 'success' });
    } else {
      uni.showToast({ title: '生成失败', icon: 'none' });
    }
  } catch (error: any) {
    console.error('生成失败:', error);
    uni.showToast({ title: error.message || '生成失败，请重试', icon: 'none' });
  } finally {
    generating.value = false;
  }
}

function useContent() {
  if (!generatedContent.value) return;

  uni.setStorageSync('ai_generated_text', generatedContent.value);
  uni.showToast({ title: '已保存，返回后自动填充', icon: 'success' });

  setTimeout(() => {
    goBack();
  }, 1500);
}

function copyContent() {
  if (!generatedContent.value) return;

  uni.setClipboardData({
    data: generatedContent.value,
    success: () => {
      uni.showToast({ title: '已复制到剪贴板', icon: 'success' });
    },
  });
}

function regenerate() {
  if (!topic.value.trim()) {
    uni.showToast({ title: '请先输入主题', icon: 'none' });
    return;
  }
  handleGenerate();
}

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

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

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #ffffff;
  border-bottom: 1px solid #f3f4f6;
  z-index: 100;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 32rpx;
}

.nav-left,
.nav-right {
  width: 100rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #4f46e5;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #1f2937;
}

.main-content {
  padding: 108rpx 32rpx 32rpx;
}

.card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  margin-bottom: 24rpx;
}

.card-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.card-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1f2937;
}

.topic-input {
  width: 100%;
  min-height: 300rpx;
  font-size: 28rpx;
  color: #1f2937;
  line-height: 1.6;
  text-align: left;
}

.word-count {
  text-align: right;
  font-size: 24rpx;
  color: #9ca3af;
  margin-top: 12rpx;
}

.generate-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 24rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
  box-shadow: 0 8rpx 24rpx rgba(79, 70, 229, 0.4);
  margin-bottom: 24rpx;
}

.generate-btn::after {
  border: none;
}

.generate-btn[disabled] {
  background: #e5e7eb;
  box-shadow: none;
}

.result-card {
  background: #ffffff;
}

.word-count-badge {
  font-size: 24rpx;
  color: #6b7280;
  background: #f3f4f6;
  padding: 6rpx 16rpx;
  border-radius: 12rpx;
}

.result-content {
  background: #f9fafb;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.result-content text {
  font-size: 28rpx;
  color: #1f2937;
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-word;
}

.result-actions {
  display: flex;
  gap: 16rpx;
}

.result-actions .action-btn {
  flex: 1;
  height: 80rpx;
  background: #f3f4f6;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #1f2937;
  border: none;
}

.result-actions .action-btn.primary {
  background: #4f46e5;
  color: #ffffff;
}

.result-actions .action-btn::after {
  border: none;
}

.generating-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 4rpx solid #e5e7eb;
  border-top-color: #4f46e5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 24rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.tip-text {
  font-size: 28rpx;
  color: #6b7280;
}
</style>
