import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Button, 
  Space, 
  message, 
  Typography, 
  Spin, 
  Card,
  Modal,
  List,
  Tag,
  Alert,
  Divider,
  Row,
  Col
} from 'antd';
import { 
  ArrowLeftOutlined, 
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  RobotOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { storage } from '../utils/indexedDB';
import { Novel, Chapter } from '../types';
import { useOllama } from '../contexts/OllamaContext';
import { NovelSettingManager } from '../utils/novelSettingManager';

const { Text, Title } = Typography;

const NovelDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [novel, setNovel] = useState<Novel | null>(null);
  const [chapters, setChapters] = useState<Chapter[]>([]);
  const [loading, setLoading] = useState(false);
  const [generatingChapter, setGeneratingChapter] = useState<number | null>(null); // 正在生成章节内容的章节号
  const [generatingOutline, setGeneratingOutline] = useState<number | null>(null); // 正在生成标题和细纲的章节号
  const [regeneratingTitle, setRegeneratingTitle] = useState<number | null>(null); // 正在重新生成标题的章节号
  const [regeneratingOutline, setRegeneratingOutline] = useState<number | null>(null); // 正在重新生成细纲的章节号
  const [regeneratingContent, setRegeneratingContent] = useState<string | null>(null); // 正在重新生成内容的章节ID
  const [chapterModalVisible, setChapterModalVisible] = useState(false);
  const [viewingChapter, setViewingChapter] = useState<Chapter | null>(null);
  const [plannedChapterModalVisible, setPlannedChapterModalVisible] = useState(false);
  const [viewingPlannedChapter, setViewingPlannedChapter] = useState<any>(null);
  const [settingsModalVisible, setSettingsModalVisible] = useState(false);
  
  const { chat } = useOllama();

  useEffect(() => {
    if (id) {
      loadNovelData();
    }
  }, [id]);

  const loadNovelData = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const novels = await storage.getNovels();
      const currentNovel = novels.find((n: Novel) => n.id === id);
      
      if (!currentNovel) {
        message.error('小说不存在');
        navigate('/novels');
        return;
      }
      
      setNovel(currentNovel);
      const novelChapters = await storage.getChapters(id);
      setChapters(novelChapters.sort((a: Chapter, b: Chapter) => a.chapterNumber - b.chapterNumber));
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleViewChapter = (chapter: Chapter) => {
    // 从最新的规划章节中获取最新的标题和细纲
    const latestPlannedChapter = novel?.generatedSettings?.chapters?.find(
      (ch: any) => ch.chapterNumber === chapter.chapterNumber
    );
    
    // 如果有最新的规划信息，合并到当前章节中
    const updatedChapter = latestPlannedChapter ? {
      ...chapter,
      title: latestPlannedChapter.title,
      outline: latestPlannedChapter.outline
    } : chapter;
    
    setViewingChapter(updatedChapter);
    setChapterModalVisible(true);
  };

  const handleEditChapter = (chapter: Chapter) => {
    navigate(`/novels/${id}/chapter/${chapter.id}`);
  };

  const handleDeleteChapter = async (chapterId: string) => {
    try {
      await storage.deleteChapter(chapterId);
      await loadNovelData();
      message.success('章节删除成功');
    } catch (error) {
      message.error('删除章节失败');
    }
  };

  // 清空章节内容
  const handleClearChapterContent = async (chapter: Chapter) => {
    Modal.confirm({
      title: '确认清空章节内容',
      content: `确定要清空第${chapter.chapterNumber}章《${chapter.title}》的内容吗？清空后章节将显示为暂未生成内容状态。`,
      okText: '确认清空',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          // 清空章节内容，但保留章节记录
          const clearedChapter: Chapter = {
            ...chapter,
            content: '',
            updatedAt: new Date().toISOString()
          };

          await storage.updateChapter(chapter.id, {
            content: '',
            updatedAt: new Date().toISOString()
          });

          // 重新加载数据以确保所有状态一致
          await loadNovelData();
          
          // 重新获取更新后的章节信息用于弹窗显示
          if (novel) {
            const updatedChapters = await storage.getChapters(novel.id);
            const latestChapter = updatedChapters.find(ch => ch.id === chapter.id);
            
            // 立即更新查看中的章节状态，确保弹窗实时更新显示空状态
            if (latestChapter) {
              setViewingChapter(latestChapter);
            }
          }

          message.success(`第${chapter.chapterNumber}章内容已清空`);
        } catch (error) {
          message.error('清空章节内容失败');
        }
      }
    });
  };


  const handleGenerateSpecificChapter = async (plannedChapter: any) => {
    if (!novel || !novel.generatedSettings) return;

    try {
      setGeneratingChapter(plannedChapter.chapterNumber); // 设置专门的加载状态

      // 生成章节上下文（基于novel_setting.md + 章节标题 + 章节细节 + 前一章内容）
      const context = NovelSettingManager.generateChapterContext(
        novel,
        plannedChapter.chapterNumber,
        chapters,
        novel.generatedSettings,
        plannedChapter.title,
        plannedChapter.outline
      );

      const response = await chat(context, `为《${novel.title}》创作第${plannedChapter.chapterNumber}章`);
      
      // 创建新章节
      const newChapter: Chapter = {
        id: Date.now().toString(),
        novelId: novel.id,
        chapterNumber: plannedChapter.chapterNumber,
        title: plannedChapter.title,
        content: response,
        outline: plannedChapter.outline,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        estimatedWords: plannedChapter.estimatedWords,
        moduleNumber: plannedChapter.moduleNumber
      };

      await storage.addChapter(newChapter);
      message.success(`第${plannedChapter.chapterNumber}章生成成功`);
      
      await loadNovelData();
      
    } catch (error: any) {
      message.error(error.message || '章节生成失败，请重试');
    } finally {
      setGeneratingChapter(null); // 清除专门的加载状态
    }
  };

  const handleViewPlannedChapter = (plannedChapter: any) => {
    setViewingPlannedChapter(plannedChapter);
    setPlannedChapterModalVisible(true);
  };

  // 下载单个章节内容
  const handleDownloadChapter = (chapter: Chapter) => {
    try {
      const content = `# 第${chapter.chapterNumber}章 ${chapter.title}\n\n` +
        `字数：${chapter.content.length}字\n` +
        `创建时间：${new Date(chapter.createdAt).toLocaleString()}\n\n` +
        `---\n\n` +
        chapter.content.split('\n').map(line => line.trim()).filter(line => line).join('\n\n');

      const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `第${chapter.chapterNumber}章_${chapter.title}.md`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      message.success(`第${chapter.chapterNumber}章下载成功`);
    } catch (error) {
      message.error('章节下载失败');
    }
  };

  // 一键下载整本书
  const handleDownloadNovel = async () => {
    if (!novel || chapters.length === 0) {
      message.warning('暂无已生成的章节可下载');
      return;
    }

    try {
      message.info({ content: '正在准备下载整本书...', duration: 2 });

      // 创建一个包含所有章节的ZIP文件结构
      const novelContent = `# ${novel.title}\n\n` +
        `题材：${novel.genre}\n` +
        `章节数：${chapters.length}章\n` +
        `总字数：${chapters.reduce((sum, ch) => sum + ch.content.length, 0)}字\n` +
        `下载时间：${new Date().toLocaleString()}\n\n` +
        `---\n\n` +
        `## 目录\n\n` +
        chapters.map(ch => `- 第${ch.chapterNumber}章 ${ch.title}`).join('\n') +
        '\n\n---\n\n' +
        chapters.map(chapter =>
          `# 第${chapter.chapterNumber}章 ${chapter.title}\n\n` +
          `字数：${chapter.content.length}字\n` +
          `创建时间：${new Date(chapter.createdAt).toLocaleString()}\n\n` +
          `---\n\n` +
          chapter.content.split('\n').map(line => line.trim()).filter(line => line).join('\n\n') +
          '\n\n---\n\n'
        ).join('');

      const blob = new Blob([novelContent], { type: 'text/markdown;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${novel.title}_完整版.md`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      message.success(`《${novel.title}》完整版下载成功，包含${chapters.length}个章节`);
    } catch (error) {
      message.error('整书下载失败');
    }
  };

  // 生成单个章节的标题和细纲
  const handleGenerateChapterOutline = async (chapterNumber: number) => {
    if (!novel || !novel.generatedSettings) return;

    try {
      setGeneratingOutline(chapterNumber); // 设置专门的标题细纲生成加载状态

      const settings = novel.generatedSettings;
      const params = {
        targetWordCount: settings.targetWordCount,
        chapterCount: settings.chapterCount,
        moduleCount: settings.moduleCount,
        avgWordsPerChapter: Math.round(settings.targetWordCount / settings.chapterCount),
        wordsPerChapterMin: 900,
        wordsPerChapterMax: 1200
      };

      // 计算当前章节应该属于哪个模块
      const moduleNumber = Math.min(Math.ceil(chapterNumber / Math.ceil(params.chapterCount / params.moduleCount)), params.moduleCount);

      message.info({ content: `正在生成第${chapterNumber}章的标题和细纲...`, duration: 2 });

      // 获取现有章节信息
      const currentChapters = settings.chapters || [];
      
      const chapterPrompt = `基于以下小说设定，为第${chapterNumber}章生成详细规划。

## 小说基础设定

### 📖 故事大纲
${settings.storyOutline}

### 🏗️ 情节结构
${settings.plotStructure}

### 👥 人物设定
${settings.characters}

## 章节规划要求

**当前章节**：第${chapterNumber}章（共${params.chapterCount}章）
**所属模块**：模块${moduleNumber}
**每章字数**：${params.wordsPerChapterMin}-${params.wordsPerChapterMax}字

${currentChapters.length > 0 ? `## 前面章节概览\n\n${currentChapters.filter((ch: any) => ch.chapterNumber < chapterNumber).slice(-3).map((ch: any) => 
  `第${ch.chapterNumber}章：${ch.title}\n细纲：${ch.outline?.substring(0, 50)}...`
).join('\n\n')}\n\n` : ''}

请按照以下格式生成第${chapterNumber}章的完整规划：

第${chapterNumber}章：章节标题 - 模块${moduleNumber}
细纲：本章的详细细纲描述，包括主要情节、人物发展、冲突转折等（100-200字）。
预计字数：1050字（范围900-1200字）

⚠️ **重要提醒**：
1. 章节细纲必须控制在100-200字之间，既要详细又不能过长
2. 要与前面章节自然衔接${chapterNumber > 1 ? '（这是后续章节的延续）' : '（这是开篇章节）'}
3. 严格按照格式生成，确保能正确解析

请开始生成第${chapterNumber}章的详细规划：`;

      const chapterResponse = await chat(chapterPrompt, `小说《${novel.title}》第${chapterNumber}章规划`);
      
      // 解析单个章节
      const parsedChapter = parseSingleChapter(chapterResponse, chapterNumber, moduleNumber, params);
      
      // 检查解析是否成功
      if (!parsedChapter || !parsedChapter.title || !parsedChapter.outline) {
        throw new Error('章节解析失败，请重试');
      }
      
      // 标记为已完成
      parsedChapter.status = 'completed';
      
      // 更新generatedSettings中的章节信息
      const updatedChapters = settings.chapters.map((ch: any) => 
        ch.chapterNumber === chapterNumber ? parsedChapter : ch
      );
      
      const updatedSettings = {
        ...settings,
        chapters: updatedChapters
      };
      
      // 保存到数据库
      await storage.updateNovel(novel.id, {
        generatedSettings: updatedSettings
      });
      
      // 更新本地状态
      setNovel({
        ...novel,
        generatedSettings: updatedSettings
      });
      
      message.success(`第${chapterNumber}章的标题和细纲生成成功！`);
      
    } catch (error: any) {
      message.error(error.message || '章节标题和细纲生成失败，请重试');
    } finally {
      setGeneratingOutline(null); // 清除专门的标题细纲生成加载状态
    }
  };

  // 解析单个章节
  const parseSingleChapter = (response: string, chapterNumber: number, moduleNumber: number, metadata: any) => {
    const lines = response.split('\n');
    let chapter: any = {
      chapterNumber: chapterNumber,
      title: `第${chapterNumber}章`,
      moduleNumber: moduleNumber,
      outline: '',
      estimatedWords: metadata.avgWordsPerChapter
    };

    let foundChapter = false;
    let inOutline = false;

    lines.forEach(line => {
      const trimmedLine = line.trim();
      
      // 匹配章节标题行：第1章：意外穿越 - 模块1
      const chapterMatch = trimmedLine.match(/第(\d+)章[：:]\s*(.+?)\s*[-—]\s*模块(\d+)/);
      if (chapterMatch) {
        const matchedChapterNum = parseInt(chapterMatch[1]);
        if (matchedChapterNum === chapterNumber) {
          chapter.title = chapterMatch[2].trim();
          chapter.moduleNumber = parseInt(chapterMatch[3]);
          foundChapter = true;
        }
      } else if (trimmedLine.includes('细纲：')) {
        // 开始收集细纲内容
        const outlineStart = trimmedLine.indexOf('细纲：') + 3;
        chapter.outline = trimmedLine.substring(outlineStart).trim();
        inOutline = true;
      } else if (trimmedLine.includes('预计字数：')) {
        // 解析字数
        const wordMatch = trimmedLine.match(/(\d+)/);
        if (wordMatch) {
          chapter.estimatedWords = parseInt(wordMatch[1]);
        }
        inOutline = false; // 细纲结束
      } else if (inOutline && trimmedLine && !trimmedLine.includes('第') && !trimmedLine.includes('模块')) {
        // 继续收集细纲内容
        if (chapter.outline) {
          chapter.outline += ' ' + trimmedLine;
        } else {
          chapter.outline = trimmedLine;
        }
      }
    });

    // 如果没有找到章节标题，使用默认值
    if (!foundChapter) {
      console.warn(`章节${chapterNumber}解析失败，使用默认值`);
      chapter.title = `第${chapterNumber}章`;
    }

    // 确保细纲不为空
    if (!chapter.outline) {
      chapter.outline = `第${chapterNumber}章的详细细纲（待补充）`;
    }

    return chapter;
  };

  // AI重新修改章节标题
  const handleRegenerateTitle = async (chapterNumber: number) => {
    if (!novel || !novel.generatedSettings) return;

    try {
      setRegeneratingTitle(chapterNumber);

      const settings = novel.generatedSettings;
      const currentChapter = settings.chapters.find((ch: any) => ch.chapterNumber === chapterNumber);
      
      if (!currentChapter) {
        throw new Error('章节不存在');
      }

      // 获取前后章节信息
      const prevChapter = settings.chapters.find((ch: any) => ch.chapterNumber === chapterNumber - 1);
      const nextChapter = settings.chapters.find((ch: any) => ch.chapterNumber === chapterNumber + 1);

      const titlePrompt = `基于以下小说设定和上下文信息，为第${chapterNumber}章重新生成一个更吸引人的标题。

## 小说基础设定

### 📖 故事大纲
${settings.storyOutline}

### 🏗️ 情节结构
${settings.plotStructure}

### 👥 人物设定
${settings.characters}

## 当前章节信息
章节编号：第${chapterNumber}章
当前标题：${currentChapter.title}
章节细纲：${currentChapter.outline}
所属模块：${currentChapter.moduleNumber}

${prevChapter ? `## 前一章信息
章节编号：第${prevChapter.chapterNumber}章
章节标题：${prevChapter.title}
章节细纲：${prevChapter.outline}

` : ''}${nextChapter ? `## 后一章信息
章节编号：第${nextChapter.chapterNumber}章
章节标题：${nextChapter.title}
章节细纲：${nextChapter.outline}

` : ''}请为第${chapterNumber}章重新生成一个标题。标题要求：
1. 要能体现章节核心内容
2. 要有吸引人和文学性
3. 字数控制在4-10个字
4. 符合小说整体风格
5. ${prevChapter ? `要与前一章《${prevChapter.title}》自然衔接` : '作为开篇章节要吸引读者'}
6. ${nextChapter ? `要为后一章《${nextChapter.title}》做好铺垫` : '作为结局章节要有圆满感'}

请直接返回新标题，不需要其他说明。`;

      const newTitle = await chat(titlePrompt, `重新生成第${chapterNumber}章标题`);
      
      // 更新章节标题
      const updatedChapters = settings.chapters.map((ch: any) => 
        ch.chapterNumber === chapterNumber ? { ...ch, title: newTitle.trim() } : ch
      );
      
      const updatedSettings = {
        ...settings,
        chapters: updatedChapters
      };
      
      // 保存到数据库
      await storage.updateNovel(novel.id, {
        generatedSettings: updatedSettings
      });
      
      // 更新本地状态
      setNovel({
        ...novel,
        generatedSettings: updatedSettings
      });
      
      // 更新查看中的规划章节
      if (viewingPlannedChapter?.chapterNumber === chapterNumber) {
        setViewingPlannedChapter({
          ...viewingPlannedChapter,
          title: newTitle.trim()
        });
      }
      
      message.success(`第${chapterNumber}章标题已更新为：${newTitle.trim()}`);
      
    } catch (error: any) {
      message.error(error.message || '标题重新生成失败，请重试');
    } finally {
      setRegeneratingTitle(null);
    }
  };

  // AI重新修改章节细纲
  const handleRegenerateOutline = async (chapterNumber: number) => {
    if (!novel || !novel.generatedSettings) return;

    try {
      setRegeneratingOutline(chapterNumber);

      const settings = novel.generatedSettings;
      const currentChapter = settings.chapters.find((ch: any) => ch.chapterNumber === chapterNumber);
      
      if (!currentChapter) {
        throw new Error('章节不存在');
      }

      // 获取前后章节信息
      const prevChapter = settings.chapters.find((ch: any) => ch.chapterNumber === chapterNumber - 1);
      const nextChapter = settings.chapters.find((ch: any) => ch.chapterNumber === chapterNumber + 1);

      // 获取已生成的前一章内容作为上下文参考
      let prevChapterContent = '';
      if (prevChapter) {
        const prevCreatedChapter = chapters.find(ch => ch.chapterNumber === prevChapter.chapterNumber);
        if (prevCreatedChapter) {
          prevChapterContent = `\n### 前一章实际内容参考\n${prevCreatedChapter.content.substring(0, 300)}...`;
        }
      }

      const outlinePrompt = `基于以下小说设定和上下文信息，为第${chapterNumber}章重新生成更详细的细纲。

## 小说基础设定

### 📖 故事大纲
${settings.storyOutline}

### 🏗️ 情节结构
${settings.plotStructure}

### 👥 人物设定
${settings.characters}

## 当前章节信息
章节编号：第${chapterNumber}章
章节标题：${currentChapter.title}
当前细纲：${currentChapter.outline}
所属模块：${currentChapter.moduleNumber}

${prevChapter ? `## 前一章信息
章节编号：第${prevChapter.chapterNumber}章
章节标题：${prevChapter.title}
章节细纲：${prevChapter.outline}${prevChapterContent}

` : ''}${nextChapter ? `## 后一章信息
章节编号：第${nextChapter.chapterNumber}章
章节标题：${nextChapter.title}
章节细纲：${nextChapter.outline}

` : ''}请为第${chapterNumber}章重新生成细纲，要求：
1. 详细描述本章的主要情节和冲突
2. 包含人物发展和情感变化
3. 设置合理的情节转折点
4. ${prevChapter ? `要从前一章《${prevChapter.title}》的情节自然延续` : '作为开篇章节要设定好故事基调'}
5. ${nextChapter ? `要为后一章《${nextChapter.title}》的情节做好铺垫和伏笔` : '作为结局章节要圆满收尾'}
6. 字数控制在100-200字
7. 细纲要具体可操作，避免过于抽象

请直接返回新细纲，不需要其他说明。`;

      const newOutline = await chat(outlinePrompt, `重新生成第${chapterNumber}章细纲`);
      
      // 更新章节细纲
      const updatedChapters = settings.chapters.map((ch: any) => 
        ch.chapterNumber === chapterNumber ? { ...ch, outline: newOutline.trim() } : ch
      );
      
      const updatedSettings = {
        ...settings,
        chapters: updatedChapters
      };
      
      // 保存到数据库
      await storage.updateNovel(novel.id, {
        generatedSettings: updatedSettings
      });
      
      // 更新本地状态
      setNovel({
        ...novel,
        generatedSettings: updatedSettings
      });
      
      // 更新查看中的规划章节
      if (viewingPlannedChapter?.chapterNumber === chapterNumber) {
        setViewingPlannedChapter({
          ...viewingPlannedChapter,
          outline: newOutline.trim()
        });
      }
      
      message.success(`第${chapterNumber}章细纲已更新`);
      
    } catch (error: any) {
      message.error(error.message || '细纲重新生成失败，请重试');
    } finally {
      setRegeneratingOutline(null);
    }
  };

  // AI重新修改章节内容
  const handleRegenerateContent = async (chapter: Chapter) => {
    if (!novel || !novel.generatedSettings) return;

    try {
      setRegeneratingContent(chapter.id);

      // 获取最新的规划章节信息，确保使用最新的标题和细纲
      const plannedChapter = novel.generatedSettings.chapters.find((ch: any) => ch.chapterNumber === chapter.chapterNumber);
      
      if (!plannedChapter) {
        throw new Error('章节规划不存在');
      }

      // 生成新的章节内容，使用最新的标题和细纲
      const context = NovelSettingManager.generateChapterContext(
        novel,
        chapter.chapterNumber,
        chapters.filter(ch => ch.chapterNumber !== chapter.chapterNumber), // 排除当前章节
        novel.generatedSettings,
        plannedChapter.title, // 使用最新的标题
        plannedChapter.outline // 使用最新的细纲
      );

      const regeneratePrompt = `${context}

## 原章节内容参考
${chapter.content.substring(0, 500)}...

请基于以上设定，为《${novel.title}》重新创作第${chapter.chapterNumber}章《${plannedChapter.title}》内容。要求：
1. 严格按照章节细纲《${plannedChapter.outline}》来创作
2. 保持章节核心情节不变
3. 优化文字表达和细节描写
4. 增强人物性格和情感表达
5. 提升文学性和可读性
6. 字数控制在${plannedChapter.estimatedWords || 1050}字左右`;

      const newContent = await chat(regeneratePrompt, `重新创作第${chapter.chapterNumber}章《${plannedChapter.title}》内容`);
      
      // 更新章节内容，使用最新的标题和细纲
      const updatedChapter: Chapter = {
        ...chapter,
        title: plannedChapter.title, // 使用最新的标题
        outline: plannedChapter.outline, // 使用最新的细纲
        content: newContent,
        updatedAt: new Date().toISOString()
      };

      await storage.updateChapter(chapter.id, {
        title: plannedChapter.title, // 同步更新标题
        outline: plannedChapter.outline, // 同步更新细纲
        content: newContent,
        updatedAt: new Date().toISOString()
      });
      
      // 重新加载数据以确保所有状态一致
      await loadNovelData();
      
      // 重新获取更新后的章节信息用于弹窗显示
      if (novel) {
        const updatedChapters = await storage.getChapters(novel.id);
        const latestChapter = updatedChapters.find(ch => ch.id === chapter.id);
        
        // 立即更新查看中的章节状态，确保弹窗中的内容实时更新
        if (latestChapter) {
          setViewingChapter({
            ...latestChapter,
            title: plannedChapter.title, // 确保使用最新标题
            outline: plannedChapter.outline // 确保使用最新细纲
          });
        }
      }
      
      message.success(`第${chapter.chapterNumber}章《${plannedChapter.title}》内容已重新生成`);
      
    } catch (error: any) {
      message.error(error.message || '章节内容重新生成失败，请重试');
    } finally {
      setRegeneratingContent(null);
    }
  };

  if (loading || !novel) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" tip={loading ? "加载中..." : ""} />
      </div>
    );
  }

  return (
    <div>
      {/* AI生成加载遮罩 */}
      {(generatingChapter !== null || generatingOutline !== null || regeneratingTitle !== null || regeneratingOutline !== null || regeneratingContent !== null) && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000,
          backdropFilter: 'blur(4px)'
        }}>
          <div style={{
            background: 'white',
            padding: '40px',
            borderRadius: '12px',
            textAlign: 'center',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
            maxWidth: '400px'
          }}>
            <Spin size="large" />
            <div style={{ marginTop: '20px', fontSize: '16px', fontWeight: 500, color: '#262626' }}>
              {generatingChapter !== null && `正在生成第${generatingChapter}章内容...`}
              {generatingOutline !== null && `正在生成第${generatingOutline}章标题和细纲...`}
              {regeneratingTitle !== null && `正在重新生成第${regeneratingTitle}章标题...`}
              {regeneratingOutline !== null && `正在重新生成第${regeneratingOutline}章细纲...`}
              {regeneratingContent !== null && `正在重新生成章节内容...`}
            </div>
            <div style={{ marginTop: '8px', fontSize: '14px', color: '#8c8c8c' }}>
              AI创作需要一些时间，请耐心等待
            </div>
          </div>
        </div>
      )}

      {/* 头部信息 */}
      <Card>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space>
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/novels')}
            >
              返回列表
            </Button>
            <Title level={3} style={{ margin: 0 }}>{novel.title}</Title>
            <Tag color="blue">{novel.genre}</Tag>
            {novel.generatedSettings && (
              <Tag color="green">已完善设定</Tag>
            )}
          </Space>
          
          {novel.generatedSettings && (
            <Space>
              {chapters.length > 0 && (
                <Button 
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={handleDownloadNovel}
                >
                  下载整书
                </Button>
              )}
              <Button 
                icon={<EyeOutlined />}
                onClick={() => setSettingsModalVisible(true)}
              >
                查看设定
              </Button>
            </Space>
          )}
        </div>

        {!novel.generatedSettings && (
          <Alert
            message="需要完善设定"
            description="请先使用AI生成小说设定，然后才能开始创作章节"
            type="warning"
            showIcon
            action={
              <Button 
                type="primary" 
                size="small"
                icon={<RobotOutlined />}
                onClick={() => navigate(`/novels/${id}/generate`)}
              >
                完善设定
              </Button>
            }
            style={{ marginTop: '16px' }}
          />
        )}

        {novel.generatedSettings && (
          <Card 
            size="small" 
            style={{ marginTop: '16px', background: '#f0f9ff' }}
          >
            <Row gutter={16}>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <Text type="secondary">目标字数</Text>
                  <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff', marginTop: '4px' }}>
                    {novel.generatedSettings.targetWordCount.toLocaleString()}字
                  </div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <Text type="secondary">章节数量</Text>
                  <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff', marginTop: '4px' }}>
                    {novel.generatedSettings.chapterCount}章
                  </div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <Text type="secondary">已完成</Text>
                  <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#52c41a', marginTop: '4px' }}>
                    {chapters.length}章
                  </div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <Text type="secondary">完成进度</Text>
                  <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#fa8c16', marginTop: '4px' }}>
                    {novel.generatedSettings.chapterCount > 0 
                      ? Math.round((chapters.length / novel.generatedSettings.chapterCount) * 100) 
                      : 0}%
                  </div>
                </div>
              </Col>
            </Row>
          </Card>
        )}
      </Card>

      {/* 章节列表 */}
      <Card 
        title="章节列表" 
        style={{ marginTop: '16px' }}
      >
        {novel.generatedSettings?.chapters && novel.generatedSettings.chapters.length > 0 ? (
          <div>
            {/* 显示AI生成的设定章节 */}
            <div style={{ marginBottom: '16px' }}>
              <Alert
                message="章节规划"
                description={`以下是AI生成的${novel.generatedSettings.chapters.length}个章节规划，显示每个章节的标题、细纲和预计字数等信息。`}
                type="info"
                showIcon
                style={{ marginBottom: '16px' }}
              />
              
              <div style={{ 
                display: 'grid', 
                gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', 
                gap: '12px' 
              }}>
                {novel.generatedSettings.chapters.map((plannedChapter) => {
                  const createdChapter = chapters.find(c => c.chapterNumber === plannedChapter.chapterNumber);
                  return (
                    <Card
                      key={plannedChapter.chapterNumber}
                      size="small"
                      hoverable
                      style={{ 
                        border: (createdChapter && createdChapter.content.length > 0) ? '2px solid #52c41a' : plannedChapter.status === 'pending' ? '2px dashed #faad14' : '1px solid #f0f0f0',
                        borderRadius: '6px',
                        background: (createdChapter && createdChapter.content.length > 0) ? '#f6ffed' : plannedChapter.status === 'pending' ? '#fffbe6' : 'white'
                      }}
                      actions={[
                        <Button 
                          key="view"
                          type="text"
                          size="small"
                          icon={<EyeOutlined />}
                          onClick={() => handleViewPlannedChapter(plannedChapter)}
                        >
                          查看规划
                        </Button>,
                        plannedChapter.status === 'pending' ? (
                          <Button 
                            key="generateOutline"
                            type="primary"
                            size="small"
                            icon={<RobotOutlined />}
                            onClick={() => handleGenerateChapterOutline(plannedChapter.chapterNumber)}
                            loading={generatingOutline === plannedChapter.chapterNumber}
                            disabled={generatingOutline !== null}
                          >
                            {generatingOutline === plannedChapter.chapterNumber ? '生成中...' : '生成标题+细纲'}
                          </Button>
                        ) : createdChapter ? (
                          <>
                            <Button 
                              key="viewCreated"
                              type="text"
                              size="small"
                              icon={<EyeOutlined />}
                              onClick={() => handleViewChapter(createdChapter!)}
                            >
                              查看内容
                            </Button>
                            {createdChapter.content.length > 0 && (
                              <Button 
                                key="downloadChapter"
                                type="text"
                                size="small"
                                icon={<DownloadOutlined />}
                                onClick={() => handleDownloadChapter(createdChapter!)}
                              >
                                下载
                              </Button>
                            )}
                          </>
                        ) : (
                          <Button 
                            key="generate"
                            type="primary"
                            size="small"
                            icon={<RobotOutlined />}
                            onClick={() => handleGenerateSpecificChapter(plannedChapter)}
                            loading={generatingChapter === plannedChapter.chapterNumber}
                            disabled={generatingChapter !== null}
                          >
                            {generatingChapter === plannedChapter.chapterNumber ? '生成中...' : 'AI生成'}
                          </Button>
                        )
                      ]}
                    >
                      <Card.Meta
                        title={
                          <Space>
                            <Tag color={createdChapter ? "green" : plannedChapter.status === 'pending' ? "orange" : "blue"}>
                              第{plannedChapter.chapterNumber}章
                            </Tag>
                            {plannedChapter.moduleNumber && (
                              <Tag color="cyan">模块{plannedChapter.moduleNumber}</Tag>
                            )}
                            {createdChapter && (
                              <Tag color="success">已创作</Tag>
                            )}
                            {plannedChapter.status === 'pending' && (
                              <Tag color="warning">待生成</Tag>
                            )}
                          </Space>
                        }
                        description={
                          <div>
                            <div style={{ 
                              fontWeight: 500, 
                              marginBottom: '6px',
                              fontSize: '14px',
                              color: '#262626'
                            }}>
                              {plannedChapter.title}
                            </div>
                            <div style={{ 
                              fontSize: '12px', 
                              color: '#666',
                              lineHeight: '1.5',
                              display: '-webkit-box',
                              WebkitLineClamp: 2,
                              WebkitBoxOrient: 'vertical',
                              overflow: 'hidden'
                            }}>
                              {plannedChapter.outline}
                            </div>
                            <div style={{ marginTop: '8px' }}>
                              {createdChapter && createdChapter.content.length > 0 ? (
                                <Tag color="success">
                                  已生成 {createdChapter.content.length}字
                                </Tag>
                              ) : (
                                <>
                                  <Tag color="orange">预计{plannedChapter.estimatedWords || 1050}字</Tag>
                                  <Tag color="default" style={{ marginLeft: '4px' }}>
                                    暂未生成内容
                                  </Tag>
                                </>
                              )}
                            </div>
                          </div>
                        }
                      />
                    </Card>
                  );
                })}
              </div>
            </div>
          </div>
        ) : (
          /* 没有AI生成设定的情况 */
          <>
            {chapters.length === 0 ? (
              <div style={{ 
                textAlign: 'center', 
                padding: '40px',
                color: '#8c8c8c' 
              }}>
                还没有章节，开始创作第一章吧！
              </div>
            ) : (
              <List
                dataSource={chapters}
                renderItem={(chapter) => (
                  <List.Item
                    actions={[
                      <Button 
                        icon={<EyeOutlined />}
                        size="small"
                        onClick={() => handleViewChapter(chapter)}
                      >
                        查看
                      </Button>,
                      <Button 
                        icon={<EditOutlined />}
                        size="small"
                        onClick={() => handleEditChapter(chapter)}
                      >
                        编辑
                      </Button>,
                      <Button 
                        icon={<DeleteOutlined />}
                        size="small"
                        danger
                        onClick={() => handleDeleteChapter(chapter.id)}
                      >
                        删除
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={
                        <Space>
                          <Text strong>第{chapter.chapterNumber}章 {chapter.title}</Text>
                          <Tag color="default">{chapter.content.length}字</Tag>
                        </Space>
                      }
                      description={
                        <Text type="secondary" ellipsis>
                          {chapter.content.substring(0, 100)}...
                        </Text>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </>
        )}
      </Card>

      {/* 查看章节内容弹窗 */}
      <Modal
        title={`第${viewingChapter?.chapterNumber}章 ${viewingChapter?.title}`}
        open={chapterModalVisible}
        onCancel={() => setChapterModalVisible(false)}
        width={900}
        footer={[
          <Space key="footer">
            {viewingChapter && viewingChapter.content.length > 0 && (
              <Button 
                icon={<DeleteOutlined />}
                onClick={() => handleClearChapterContent(viewingChapter)}
                danger
              >
                清空内容
              </Button>
            )}
            <Button 
              icon={<RobotOutlined />}
              onClick={() => viewingChapter && handleRegenerateContent(viewingChapter)}
              loading={regeneratingContent === viewingChapter?.id}
              disabled={regeneratingContent !== null}
              type="primary"
            >
              {viewingChapter && viewingChapter.content.length > 0 ? 'AI重新生成内容' : 'AI生成内容'}
            </Button>
            <Button onClick={() => setChapterModalVisible(false)}>
              关闭
            </Button>
          </Space>
        ]}
      >
        {viewingChapter && (
          <div>
            <div style={{ marginBottom: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <Space>
                <Text type="secondary">字数：</Text>
                <Text strong>{viewingChapter.content.length}字</Text>
                <Divider type="vertical" />
                <Text type="secondary">创建时间：</Text>
                <Text>{new Date(viewingChapter.createdAt).toLocaleString()}</Text>
                {viewingChapter.updatedAt !== viewingChapter.createdAt && (
                  <>
                    <Divider type="vertical" />
                    <Text type="secondary">更新时间：</Text>
                    <Text>{new Date(viewingChapter.updatedAt).toLocaleString()}</Text>
                  </>
                )}
              </Space>
            </div>
            <div style={{ 
              maxHeight: '60vh', 
              overflowY: 'auto',
              lineHeight: '1.8',
              padding: '16px',
              background: '#fafafa',
              borderRadius: '6px',
              minHeight: '200px'
            }}>
              {viewingChapter.content.length > 0 ? (
                <div dangerouslySetInnerHTML={{ 
                  __html: viewingChapter.content.split('\n').map(line => 
                    line.trim() ? `<p style="margin-bottom: 12px; text-indent: 2em;">${line}</p>` : '<br/>'
                  ).join('')
                }} />
              ) : (
                <div style={{ 
                  textAlign: 'center', 
                  color: '#8c8c8c', 
                  padding: '60px 20px',
                  fontSize: '16px'
                }}>
                  <div style={{ marginBottom: '16px', fontSize: '32px' }}>📝</div>
                  <div style={{ fontSize: '18px', fontWeight: 500, marginBottom: '8px' }}>暂未生成内容</div>
                  <div style={{ fontSize: '14px', marginTop: '8px' }}>
                    点击下方按钮使用AI生成章节内容
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* 查看规划章节详情弹窗 */}
      <Modal
        title={`第${viewingPlannedChapter?.chapterNumber}章规划详情：${viewingPlannedChapter?.title}`}
        open={plannedChapterModalVisible}
        onCancel={() => setPlannedChapterModalVisible(false)}
        width={700}
        footer={[
          <Button key="close" onClick={() => setPlannedChapterModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {viewingPlannedChapter && (
          <div style={{ padding: '16px 0' }}>
            <div style={{ marginBottom: '24px' }}>
              <div style={{ fontSize: '14px', color: '#595959', marginBottom: '8px' }}>
                章节编号
              </div>
              <div style={{ 
                padding: '12px', 
                background: '#f5f5f5', 
                borderRadius: '6px',
                fontSize: '16px',
                fontWeight: 500
              }}>
                第{viewingPlannedChapter.chapterNumber}章
              </div>
            </div>

            <div style={{ marginBottom: '24px' }}>
              <div style={{ fontSize: '14px', color: '#595959', marginBottom: '8px' }}>
                章节标题
              </div>
              <div style={{ 
                padding: '12px', 
                background: '#f5f5f5', 
                borderRadius: '6px',
                fontSize: '16px',
                fontWeight: 500,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <span>{viewingPlannedChapter.title}</span>
                {viewingPlannedChapter.status !== 'pending' && (
                  <Button 
                    size="small"
                    icon={<RobotOutlined />}
                    onClick={() => handleRegenerateTitle(viewingPlannedChapter.chapterNumber)}
                    loading={regeneratingTitle === viewingPlannedChapter.chapterNumber}
                    disabled={regeneratingTitle !== null}
                  >
                    AI重修
                  </Button>
                )}
              </div>
            </div>

            {viewingPlannedChapter.moduleNumber && (
              <div style={{ marginBottom: '24px' }}>
                <div style={{ fontSize: '14px', color: '#595959', marginBottom: '8px' }}>
                  所属模块
                </div>
                <div style={{ 
                  padding: '12px', 
                  background: '#f5f5f5', 
                  borderRadius: '6px'
                }}>
                  <Tag color="cyan">模块{viewingPlannedChapter.moduleNumber}</Tag>
                </div>
              </div>
            )}

            <div style={{ marginBottom: '24px' }}>
              <div style={{ fontSize: '14px', color: '#595959', marginBottom: '8px' }}>
                预计字数
              </div>
              <div style={{ 
                padding: '12px', 
                background: '#f5f5f5', 
                borderRadius: '6px'
              }}>
                <Tag color="orange">{viewingPlannedChapter.estimatedWords || 1050}字</Tag>
              </div>
            </div>

            <div style={{ marginBottom: '24px' }}>
              <div style={{ fontSize: '14px', color: '#595959', marginBottom: '8px' }}>
                章节细纲
              </div>
              <div style={{ 
                padding: '12px', 
                background: '#f5f5f5', 
                borderRadius: '6px',
                lineHeight: '1.8',
                maxHeight: '300px',
                overflowY: 'auto',
                position: 'relative'
              }}>
                {viewingPlannedChapter.outline}
                {viewingPlannedChapter.status !== 'pending' && (
                  <div style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid #e8e8e8' }}>
                    <Button 
                      size="small"
                      icon={<RobotOutlined />}
                      onClick={() => handleRegenerateOutline(viewingPlannedChapter.chapterNumber)}
                      loading={regeneratingOutline === viewingPlannedChapter.chapterNumber}
                      disabled={regeneratingOutline !== null}
                      block
                    >
                      AI重新生成细纲
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* 设定信息弹窗 */}
      <Modal
        title={
          <Space>
            <span>📊 小说设定信息</span>
            <Tag color="blue">已完善</Tag>
          </Space>
        }
        open={settingsModalVisible}
        onCancel={() => setSettingsModalVisible(false)}
        width={900}
        footer={[
          <Button key="close" onClick={() => setSettingsModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {novel.generatedSettings && (
          <div style={{ padding: '16px 0' }}>
            <Row gutter={16} style={{ marginBottom: '24px' }}>
              <Col span={6}>
                <div style={{ textAlign: 'center', padding: '16px', background: '#f0f9ff', borderRadius: '8px' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                    {novel.generatedSettings.targetWordCount.toLocaleString()}
                  </div>
                  <div style={{ fontSize: '14px', color: '#666', marginTop: '4px' }}>
                    目标字数
                  </div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center', padding: '16px', background: '#f0f9ff', borderRadius: '8px' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                    {novel.generatedSettings.chapterCount}
                  </div>
                  <div style={{ fontSize: '14px', color: '#666', marginTop: '4px' }}>
                    章节数量
                  </div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center', padding: '16px', background: '#f0f9ff', borderRadius: '8px' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                    {novel.generatedSettings.moduleCount}
                  </div>
                  <div style={{ fontSize: '14px', color: '#666', marginTop: '4px' }}>
                    模块数量
                  </div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center', padding: '16px', background: '#f0f9ff', borderRadius: '8px' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                    {Math.round(novel.generatedSettings.targetWordCount / novel.generatedSettings.chapterCount)}
                  </div>
                  <div style={{ fontSize: '14px', color: '#666', marginTop: '4px' }}>
                    每章字数
                  </div>
                </div>
              </Col>
            </Row>

            <Divider style={{ margin: '24px 0' }} />

            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: '16px' }}>
                  <h4 style={{ fontSize: '15px', fontWeight: 'bold', marginBottom: '8px' }}>📖 故事大纲</h4>
                  <div style={{ 
                    padding: '12px', 
                    background: '#f5f5f5', 
                    borderRadius: '6px',
                    lineHeight: '1.8',
                    fontSize: '14px'
                  }}>
                    {novel.generatedSettings.storyOutline || '暂无内容'}
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginBottom: '16px' }}>
                  <h4 style={{ fontSize: '15px', fontWeight: 'bold', marginBottom: '8px' }}>🏗️ 情节结构</h4>
                  <div style={{ 
                    padding: '12px', 
                    background: '#f5f5f5', 
                    borderRadius: '6px',
                    lineHeight: '1.8',
                    fontSize: '14px',
                    whiteSpace: 'pre-line',
                    maxHeight: '200px',
                    overflowY: 'auto'
                  }}>
                    {novel.generatedSettings.plotStructure || '暂无内容'}
                  </div>
                </div>
              </Col>
            </Row>

            <div style={{ marginBottom: '16px' }}>
              <h4 style={{ fontSize: '15px', fontWeight: 'bold', marginBottom: '8px' }}>👥 人物设定</h4>
              <div style={{ 
                padding: '12px', 
                background: '#f5f5f5', 
                borderRadius: '6px',
                lineHeight: '1.8',
                fontSize: '14px',
                whiteSpace: 'pre-line',
                maxHeight: '300px',
                overflowY: 'auto'
              }}>
                {novel.generatedSettings.characters || '暂无内容'}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default NovelDetail;