import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Typography, 
  Alert, 
  Space, 
  Modal, 
  message,
  Divider,
  Row,
  Col,
  Statistic,
  Progress,
  Steps,
  Descriptions,
  Input
} from 'antd';
import { 
  ClearOutlined, 
  ReloadOutlined, 
  CheckCircleOutlined, 
  ExclamationCircleOutlined,
  DatabaseOutlined,
  SettingOutlined,
  DeleteOutlined,
  SafetyOutlined,
  RocketOutlined,
  CloudUploadOutlined,
  FundOutlined
} from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;

const InitPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [initStatus, setInitStatus] = useState<{
    step: number;
    message: string;
    status: 'process' | 'finish' | 'error' | 'wait';
  }>({ step: 0, message: '等待初始化...', status: 'wait' });
  const [dbStats, setDbStats] = useState({
    novels: 0,
    chapters: 0,
    settings: 0
  });
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [isFirstRun, setIsFirstRun] = useState(false);
  const [initMode, setInitMode] = useState<'reset' | 'setup'>('reset');

  const getDbStats = async () => {
    try {
      const { storage } = await import('../utils/indexedDB');
      const novels = await storage.getNovels();
      const settings = localStorage.getItem('ollamaSettings');
      
      let totalChapters = 0;
      for (const novel of novels) {
        const chapters = await storage.getChapters(novel.id);
        totalChapters += chapters.length;
      }

      setDbStats({
        novels: novels.length,
        chapters: totalChapters,
        settings: settings ? 1 : 0
      });

      // 检查是否是首次运行
      const hasRunBefore = localStorage.getItem('aiNovelInitialized');
      const isFirstRunDetected = !hasRunBefore && novels.length === 0 && !settings;
      setIsFirstRun(isFirstRunDetected);
      
      if (isFirstRunDetected) {
        setInitMode('setup');
      }
    } catch (error) {
      console.error('获取数据库统计失败:', error);
      // 如果获取失败，可能是首次运行
      const hasRunBefore = localStorage.getItem('aiNovelInitialized');
      if (!hasRunBefore) {
        setIsFirstRun(true);
        setInitMode('setup');
      }
    }
  };

  useEffect(() => {
    getDbStats();
  }, []);

  const handleInit = async () => {
    setShowConfirmModal(true);
  };

  const confirmInit = async () => {
    setShowConfirmModal(false);
    setLoading(true);
    setCurrentStep(0);

    try {
      if (initMode === 'setup') {
        // 首次安装模式
        await firstTimeSetup();
      } else {
        // 重置模式
        await systemReset();
      }
      
      // 标记系统已初始化
      localStorage.setItem('aiNovelInitialized', new Date().toISOString());
      
      setCurrentStep(currentStep + 1);
      message.success(initMode === 'setup' ? '系统配置完成！' : '系统重置完成！');
      
      // 重新获取统计数据
      setTimeout(() => {
        getDbStats();
      }, 1000);
      
    } catch (error: any) {
      setInitStatus({
        step: currentStep + 1,
        message: `初始化失败: ${error.message}`,
        status: 'error'
      });
      message.error('系统初始化失败，请查看错误信息');
    } finally {
      setLoading(false);
    }
  };

  const firstTimeSetup = async () => {
    const setupSteps = [
      // 步骤1：初始化IndexedDB
      {
        step: 0,
        message: '正在初始化IndexedDB数据库...',
        action: async () => {
          await reinitializeIndexedDB();
        }
      },
      // 步骤2：创建默认配置
      {
        step: 1,
        message: '正在创建默认配置...',
        action: async () => {
          restoreDefaultSettings();
        }
      },
      // 步骤3：初始化技能库
      {
        step: 2,
        message: '正在初始化技能库...',
        action: async () => {
          await initializeSkills();
        }
      },
      // 步骤4：配置系统参数
      {
        step: 3,
        message: '正在配置系统参数...',
        action: async () => {
          await configureSystem();
        }
      },
      // 步骤5：验证系统状态
      {
        step: 4,
        message: '正在验证系统状态...',
        action: async () => {
          await verifySystem();
        }
      }
    ];

    for (const { step, message, action } of setupSteps) {
      setCurrentStep(step);
      setInitStatus({ step: step + 1, message, status: 'process' });
      
      await action();
      
      setInitStatus({ 
        step: step + 1, 
        message: `${message.replace('正在', '')}完成`, 
        status: 'finish' 
      });
      await sleep(800);
    }
  };

  const systemReset = async () => {
    // 步骤1：清除IndexedDB数据
    setCurrentStep(0);
    setInitStatus({ step: 1, message: '正在清除IndexedDB数据...', status: 'process' });
    
    await clearIndexedDB();
    
    setInitStatus({ step: 1, message: 'IndexedDB数据清除完成', status: 'finish' });
    await sleep(500);

    // 步骤2：清除本地存储配置
    setCurrentStep(1);
    setInitStatus({ step: 2, message: '正在清除本地存储配置...', status: 'process' });
    
    clearLocalStorage();
    
    setInitStatus({ step: 2, message: '本地存储配置清除完成', status: 'finish' });
    await sleep(500);

    // 步骤3：重新初始化IndexedDB
    setCurrentStep(2);
    setInitStatus({ step: 3, message: '正在重新初始化IndexedDB...', status: 'process' });
    
    await reinitializeIndexedDB();
    
    setInitStatus({ step: 3, message: 'IndexedDB重新初始化完成', status: 'finish' });
    await sleep(500);

    // 步骤4：恢复默认配置
    setCurrentStep(3);
    setInitStatus({ step: 4, message: '正在恢复默认配置...', status: 'process' });
    
    restoreDefaultSettings();
    
    setInitStatus({ step: 4, message: '默认配置恢复完成', status: 'finish' });
  };

  const clearIndexedDB = async () => {
    return new Promise((resolve, reject) => {
      const request = indexedDB.deleteDatabase('AINovelDatabase');
      
      request.onsuccess = () => {
        console.log('IndexedDB删除成功');
        resolve(true);
      };
      
      request.onerror = () => {
        console.error('IndexedDB删除失败');
        reject(new Error('IndexedDB删除失败'));
      };
      
      request.onblocked = () => {
        console.warn('IndexedDB删除被阻止，正在重试...');
        setTimeout(() => {
          clearIndexedDB().then(resolve).catch(reject);
        }, 1000);
      };
    });
  };

  const clearLocalStorage = () => {
    // 清除所有Ollama相关的设置
    const keysToRemove: string[] = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && (key.includes('ollama') || key.includes('model') || key.includes('settings'))) {
        keysToRemove.push(key);
      }
    }
    keysToRemove.forEach(key => localStorage.removeItem(key));
    console.log('清除了', keysToRemove.length, '个本地存储项');
  };

  const reinitializeIndexedDB = async () => {
    const { indexedDBStorage } = await import('../utils/indexedDB');
    await indexedDBStorage.init();
    console.log('IndexedDB重新初始化完成');
  };

  const restoreDefaultSettings = () => {
    // 恢复默认的Ollama设置
    const defaultSettings = {
      apiUrl: 'http://localhost:11434',
      model: '',
      temperature: 0.7,
      topP: 0.9,
      maxTokens: 2000
    };
    
    localStorage.setItem('ollamaSettings', JSON.stringify(defaultSettings));
    console.log('默认配置恢复完成');
  };

  const initializeSkills = async () => {
    // 初始化默认技能库
    const defaultSkills = [
      {
        id: 'skill_1',
        name: '小说设定生成',
        description: '根据用户的小说创意，自动生成完整的小说设定',
        category: '创作辅助',
        prompt: '你是一个专业的小说设定助手...',
        createdAt: new Date().toISOString()
      },
      {
        id: 'skill_2',
        name: '章节内容创作',
        description: '根据章节标题和细纲，自动创作具体的章节内容',
        category: '内容创作',
        prompt: '你是一个专业的小说作家...',
        createdAt: new Date().toISOString()
      }
    ];
    
    // 可以存储到 localStorage 或 IndexedDB
    localStorage.setItem('defaultSkills', JSON.stringify(defaultSkills));
    console.log('技能库初始化完成');
  };

  const configureSystem = async () => {
    // 配置其他系统参数
    const systemConfig = {
      version: '0.0.1',
      theme: 'light',
      language: 'zh-CN',
      autoSave: true,
      maxHistory: 50
    };
    
    localStorage.setItem('systemConfig', JSON.stringify(systemConfig));
    console.log('系统参数配置完成');
  };

  const verifySystem = async () => {
    // 验证各个组件是否正常工作
    const checks = [
      {
        name: 'IndexedDB',
        check: async () => {
          const { indexedDBStorage } = await import('../utils/indexedDB');
          await indexedDBStorage.init();
          return true;
        }
      },
      {
        name: '本地存储',
        check: () => {
          try {
            localStorage.setItem('test', 'test');
            localStorage.removeItem('test');
            return true;
          } catch {
            return false;
          }
        }
      }
    ];

    for (const { name, check } of checks) {
      const result = await check();
      if (!result) {
        throw new Error(`${name}验证失败`);
      }
      console.log(`${name}验证通过`);
    }
  };

  const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

  const getSteps = () => {
    if (initMode === 'setup') {
      return [
        {
          title: '初始化数据库',
          description: '创建IndexedDB数据库和存储结构',
          icon: <DatabaseOutlined />
        },
        {
          title: '创建默认配置',
          description: '设置系统默认的Ollama配置',
          icon: <SettingOutlined />
        },
        {
          title: '初始化技能库',
          description: '加载默认的AI创作技能',
          icon: <FundOutlined />
        },
        {
          title: '配置系统参数',
          description: '设置主题、语言等系统参数',
          icon: <CloudUploadOutlined />
        },
        {
          title: '验证系统状态',
          description: '检查所有组件是否正常工作',
          icon: <SafetyOutlined />
        }
      ];
    } else {
      return [
        {
          title: '清除IndexedDB',
          description: '删除所有存储的小说、章节等数据',
          icon: <DatabaseOutlined />
        },
        {
          title: '清除本地配置',
          description: '清除所有本地存储的配置信息',
          icon: <DeleteOutlined />
        },
        {
          title: '重新初始化',
          description: '重新创建数据库和存储结构',
          icon: <ReloadOutlined />
        },
        {
          title: '恢复默认配置',
          description: '设置系统的默认配置参数',
          icon: <SettingOutlined />
        }
      ];
    }
  };

  return (
    <div>
      <div style={{ marginBottom: '24px' }}>
        <Title level={2} style={{ margin: 0, display: 'flex', alignItems: 'center', gap: '12px' }}>
          {initMode === 'setup' ? (
            <RocketOutlined style={{ color: '#52c41a' }} />
          ) : (
            <ClearOutlined style={{ color: '#1890ff' }} />
          )}
          {initMode === 'setup' ? '系统初始化配置' : '系统重置'}
        </Title>
        <Text type="secondary" style={{ marginTop: '8px', display: 'block' }}>
          {initMode === 'setup' 
            ? '首次使用本系统，一键配置所有必要的组件和参数' 
            : '一键重置系统所有数据和配置到初始状态'}
        </Text>
      </div>

      {initMode === 'setup' ? (
        <Alert
          message="欢迎使用AI小说创作系统"
          description="检测到您是首次使用本系统，我们将为您自动配置必要的组件和设置，整个过程大约需要10-20秒。"
          type="info"
          showIcon
          icon={<RocketOutlined />}
          style={{ marginBottom: '24px' }}
        />
      ) : (
        <Alert
          message="危险操作警告"
          description="此操作将清除所有数据，包括小说、章节、配置等，且不可恢复。请谨慎操作！"
          type="warning"
          showIcon
          icon={<ExclamationCircleOutlined />}
          style={{ marginBottom: '24px' }}
        />
      )}

      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="小说数量"
              value={dbStats.novels}
              prefix={<DatabaseOutlined />}
              valueStyle={{ color: dbStats.novels > 0 ? '#1890ff' : '#999' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="章节数量"
              value={dbStats.chapters}
              prefix={<DatabaseOutlined />}
              valueStyle={{ color: dbStats.chapters > 0 ? '#52c41a' : '#999' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="配置文件"
              value={dbStats.settings}
              prefix={<SettingOutlined />}
              valueStyle={{ color: dbStats.settings > 0 ? '#faad14' : '#999' }}
              suffix="个"
            />
          </Card>
        </Col>
      </Row>

      <Card 
        title="初始化进度"
        extra={
          <Button
            type={initMode === 'setup' ? 'primary' : 'primary'}
            danger={initMode !== 'setup'}
            icon={initMode === 'setup' ? <RocketOutlined /> : <ClearOutlined />}
            onClick={handleInit}
            loading={loading}
            disabled={loading}
            size="large"
          >
            {loading 
              ? (initMode === 'setup' ? '配置中...' : '初始化中...') 
              : (initMode === 'setup' ? '开始配置' : '开始初始化')}
          </Button>
        }
      >
        {loading && (
          <div style={{ marginBottom: '24px' }}>
            <Steps
              current={currentStep}
              status={initStatus.status}
              items={getSteps().map((step, index) => ({
                ...step,
                status: index < currentStep ? 'finish' : 
                       index === currentStep ? initStatus.status : 'wait'
              }))}
            />
            
            <Divider />
            
            <div style={{ 
              padding: '16px', 
              background: initStatus.status === 'error' ? '#fff2f0' : 
                         initStatus.status === 'finish' ? '#f6ffed' : '#e6f7ff',
              borderRadius: '8px',
              border: `1px solid ${initStatus.status === 'error' ? '#ffccc7' : 
                                  initStatus.status === 'finish' ? '#b7eb8f' : '#91d5ff'}`
            }}>
              <Space>
                {initStatus.status === 'process' && <ReloadOutlined spin style={{ color: '#1890ff' }} />}
                {initStatus.status === 'finish' && <CheckCircleOutlined style={{ color: '#52c41a' }} />}
                {initStatus.status === 'error' && <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />}
                <Text strong>{initStatus.message}</Text>
              </Space>
            </div>
            
            {currentStep < getSteps().length && (
              <div style={{ marginTop: '16px' }}>
                <Progress 
                  percent={Math.round(((currentStep + 1) / getSteps().length) * 100)} 
                  status={initStatus.status === 'error' ? 'exception' : 'active'}
                  strokeColor={{
                    '0%': '#108ee9',
                    '100%': '#87d068',
                  }}
                />
              </div>
            )}
          </div>
        )}

        {!loading && currentStep === 0 && (
          <div>
            {initMode === 'setup' ? (
              <div>
                <Descriptions title="首次配置将执行以下操作" bordered column={1}>
                  <Descriptions.Item 
                    label={<Space><DatabaseOutlined />初始化数据库</Space>}
                  >
                    创建IndexedDB数据库和存储结构，用于存储小说、章节等数据
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><SettingOutlined />创建默认配置</Space>}
                  >
                    设置Ollama服务连接参数和AI模型配置
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><FundOutlined />初始化技能库</Space>}
                  >
                    加载默认的AI创作技能模板，如小说设定生成、章节创作等
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><CloudUploadOutlined />配置系统参数</Space>}
                  >
                    设置界面主题、语言、自动保存等系统参数
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><SafetyOutlined />验证系统状态</Space>}
                  >
                    检查数据库连接、本地存储等组件是否正常工作
                  </Descriptions.Item>
                </Descriptions>
                
                <Divider />
                
                <Alert
                  message="配置完成后您将获得"
                  description={
                    <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                      <li>完整的数据存储系统</li>
                      <li>预配置的AI模型连接参数</li>
                      <li>丰富的AI创作技能库</li>
                      <li>优化的系统使用体验</li>
                    </ul>
                  }
                  type="success"
                  showIcon
                />
              </div>
            ) : (
              <div>
                <Descriptions title="初始化将执行以下操作" bordered column={1}>
                  <Descriptions.Item 
                    label={<Space><DatabaseOutlined />清除IndexedDB</Space>}
                  >
                    删除所有存储的小说、章节、草稿等数据
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><DeleteOutlined />清除本地配置</Space>}
                  >
                    清除所有本地存储的Ollama设置和用户配置
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><ReloadOutlined />重新初始化</Space>}
                  >
                    重新创建数据库结构和存储对象
                  </Descriptions.Item>
                  <Descriptions.Item 
                    label={<Space><SettingOutlined />恢复默认配置</Space>}
                  >
                    设置系统默认的参数配置
                  </Descriptions.Item>
                </Descriptions>
                
                <Divider />
                
                <Alert
                  message="建议在以下情况下执行初始化"
                  description={
                    <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                      <li>系统出现异常数据错误</li>
                      <li>数据库损坏或无法正常访问</li>
                      <li>需要完全清除所有数据重新开始</li>
                      <li>升级到不兼容的新版本</li>
                    </ul>
                  }
                  type="info"
                  showIcon
                />
              </div>
            )}
          </div>
        )}

        {currentStep === getSteps().length && initStatus.status === 'finish' && (
          <div>
            <Alert
              message={initMode === 'setup' ? '系统配置完成！' : '系统初始化成功'}
              description={initMode === 'setup' 
                ? '所有必要的组件和参数已配置完成，系统现在可以正常使用了。'
                : '所有数据和配置已重置到初始状态，系统现在可以正常使用了。'}
              type="success"
              showIcon
              style={{ marginBottom: '16px' }}
            />
            
            <Space direction="vertical" style={{ width: '100%' }}>
              {initMode === 'setup' ? (
                <>
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>数据库已初始化</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>IndexedDB数据库和存储结构已创建完成</div>
                      </div>
                    </Space>
                  </Card>
                  
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>配置已设置</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>Ollama服务和AI模型配置已设置完成</div>
                      </div>
                    </Space>
                  </Card>
                  
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>技能库已加载</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>默认AI创作技能模板已加载完成</div>
                      </div>
                    </Space>
                  </Card>
                  
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>系统已就绪</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>所有组件运行正常，可以开始创作之旅</div>
                      </div>
                    </Space>
                  </Card>
                </>
              ) : (
                <>
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>IndexedDB已重置</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>数据库已重新创建，可以开始新的创作</div>
                      </div>
                    </Space>
                  </Card>
                  
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>配置已恢复</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>系统配置已恢复到默认设置</div>
                      </div>
                    </Space>
                  </Card>
                  
                  <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <Space>
                      <SafetyOutlined style={{ color: '#52c41a', fontSize: '20px' }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>系统就绪</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>所有组件运行正常，可以开始使用</div>
                      </div>
                    </Space>
                  </Card>
                </>
              )}
            </Space>
          </div>
        )}
      </Card>

      <Modal
        title={
          <Space>
            {initMode === 'setup' ? (
              <RocketOutlined style={{ color: '#52c41a' }} />
            ) : (
              <ExclamationCircleOutlined style={{ color: '#faad14' }} />
            )}
            {initMode === 'setup' ? '确认开始系统配置' : '确认初始化系统'}
          </Space>
        }
        open={showConfirmModal}
        onOk={confirmInit}
        onCancel={() => setShowConfirmModal(false)}
        okText={initMode === 'setup' ? '开始配置' : '确认初始化'}
        cancelText="取消"
        okButtonProps={{ danger: initMode !== 'setup' }}
      >
        {initMode === 'setup' ? (
          <Alert
            message="准备开始系统配置"
            description={
              <div>
                <p>系统将为您自动配置以下组件：</p>
                <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                  <li>创建IndexedDB数据库结构</li>
                  <li>设置Ollama服务连接参数</li>
                  <li>加载默认AI创作技能库</li>
                  <li>配置系统界面和功能参数</li>
                  <li>验证所有组件正常工作</li>
                </ul>
                <p style={{ color: '#52c41a', fontWeight: 'bold' }}>
                  整个过程大约需要10-20秒，请耐心等待。
                </p>
              </div>
            }
            type="info"
            showIcon
          />
        ) : (
          <Alert
            message="此操作不可逆"
            description={
              <div>
                <p>您即将执行系统初始化操作，这将：</p>
                <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                  <li><strong>永久删除</strong>所有小说数据（{dbStats.novels}个小说）</li>
                  <li><strong>永久删除</strong>所有章节内容（{dbStats.chapters}个章节）</li>
                  <li><strong>清除所有</strong>配置和设置</li>
                  <li><strong>重置系统</strong>到初始状态</li>
                </ul>
                <p style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
                  这些数据将无法恢复！请确保已做好数据备份。
                </p>
              </div>
            }
            type="error"
            showIcon
          />
        )}
        
        {initMode !== 'setup' && (
          <div style={{ marginTop: '16px' }}>
            <Text strong>请输入 "CONFIRM" 来确认此操作：</Text>
            <Input.Password 
              placeholder="输入 CONFIRM 确认"
              onChange={(e) => {
                // 可以添加额外的确认逻辑
              }}
              style={{ marginTop: '8px' }}
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default InitPage;