import React, { useState, useEffect } from 'react';
import { Layout, Menu, Alert, Space, Button } from 'antd';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { BookOutlined, SettingOutlined, AppstoreOutlined, ReloadOutlined, RobotOutlined, ThunderboltOutlined, ClearOutlined, MessageOutlined } from '@ant-design/icons';
import { indexedDBStorage } from '../utils/indexedDB';
import { useOllama } from '../contexts/OllamaContext';
import Header from './Header';
import './MainLayout.css';

const { Sider, Content, Footer } = Layout;

const MainLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [showAlert, setShowAlert] = useState<boolean>(true);
  const [dbInitialized, setDbInitialized] = useState<boolean>(false);
  const { status, refreshModels } = useOllama();

  const menuItems = [
    {
      key: '/novels',
      icon: <BookOutlined />,
      label: '小说管理',
    },
    {
      key: '/chat',
      icon: <MessageOutlined />,
      label: '聊天',
      children: [
        {
          key: '/chat/conversations',
          icon: <MessageOutlined />,
          label: '会话',
        },
      ],
    },
    {
      key: '/agents',
      icon: <RobotOutlined />,
      label: '智能体',
      children: [
        {
          key: '/agents/skills',
          icon: <ThunderboltOutlined />,
          label: '技能',
        },
      ],
    },
    {
      key: '/settings',
      icon: <SettingOutlined />,
      label: '设置',
      children: [
        {
          key: '/settings/model',
          icon: <AppstoreOutlined />,
          label: '模型',
        },
        {
          key: '/settings/init',
          icon: <ClearOutlined />,
          label: '初始化',
        },
      ],
    },
  ];

  const handleMenuClick = ({ key }: { key: string }) => {
    navigate(key);
  };

  useEffect(() => {
    // 初始化 IndexedDB
    const initDB = async () => {
      try {
        await indexedDBStorage.init();
        setDbInitialized(true);
      } catch (error) {
        console.error('Failed to initialize IndexedDB:', error);
      }
    };
    
    initDB();
  }, []);


  const formatModelSize = (bytes?: number) => {
    if (!bytes) return '未知大小';
    const gb = bytes / (1024 * 1024 * 1024);
    return `${gb.toFixed(2)} GB`;
  };

  const getCurrentModelInfo = () => {
    // 如果没有配置模型，直接显示"暂未配置"
    if (!status.currentModel) {
      return '暂未配置';
    }
    
    // 检查模型是否在本地已安装列表中
    const model = status.availableModels.find(m => m.name === status.currentModel);
    if (!model) {
      // 模型未安装，只显示模型名称
      return status.currentModel;
    }
    
    // 模型已安装且可用，显示详细信息
    return `${status.currentModel} (${formatModelSize(model.size)})`;
  };

  const getCurrentModelStatus = () => {
    // 返回当前模型的状态类型
    if (!status.currentModel) {
      return 'error'; // 未配置
    }
    
    if (!status.isConnected) {
      return 'warning'; // 服务未连接
    }
    
    const model = status.availableModels.find(m => m.name === status.currentModel);
    if (!model) {
      return 'warning'; // 模型未安装
    }
    
    return 'success'; // 正常
  };

  return (
    <Layout style={{ minHeight: '100vh', background: '#f5f7fa' }}>
      <Header />
      <Sider 
        width={220} 
        style={{ 
          background: '#ffffff',
          borderRight: '1px solid #e8e8e8',
          height: '100vh',
          position: 'fixed',
          left: 0,
          top: 0,
          bottom: 0,
          boxShadow: '2px 0 8px rgba(0,0,0,0.06)',
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        <div style={{ 
          position: 'relative',
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          height: '100%'
        }}>
        <div style={{ 
          height: '64px', 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center',
          borderBottom: '1px solid #f0f0f0',
          padding: '0 16px',
          gap: '8px'
        }}>
          <RobotOutlined 
            style={{ 
              color: '#1890ff', 
              fontSize: '20px'
            }}
            className="spin-animation"
          />
          <div style={{ 
            color: '#1890ff', 
            fontSize: '16px', 
            fontWeight: 600,
            textAlign: 'center',
            letterSpacing: '0.5px'
          }}>
            AI 小说创作
          </div>
        </div>
        

        <Menu
          mode="inline"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={handleMenuClick}
          style={{ 
            borderRight: 0,
            background: 'transparent',
            fontSize: '14px',
            flex: 1,
            overflowY: 'auto',
            paddingBottom: '50px'
          }}
        />
        
        {/* 底部品牌信息 - 悬浮固定 */}
        <div 
          onClick={() => window.open('https://juejin.cn/user/3634340804698010', '_blank')}
          style={{
            position: 'absolute',
            bottom: 0,
            left: 0,
            right: 0,
            padding: '12px 16px',
            textAlign: 'center',
            borderTop: '1px solid #f0f0f0',
            background: '#fafafa',
            zIndex: 10,
            boxShadow: '0 -2px 8px rgba(0,0,0,0.05)',
            cursor: 'pointer',
            transition: 'all 0.3s ease'
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = '#f0f9ff';
            e.currentTarget.style.boxShadow = '0 -2px 12px rgba(24, 144, 255, 0.1)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = '#fafafa';
            e.currentTarget.style.boxShadow = '0 -2px 8px rgba(0,0,0,0.05)';
          }}
        >
          <div style={{
            fontSize: '11px',
            color: '#8c8c8c',
            fontWeight: 500,
            letterSpacing: '0.3px',
            lineHeight: '1.5'
          }}>
            <div>代码老中医出品</div>
            <div style={{ 
              fontSize: '10px', 
              color: '#bfbfbf',
              marginTop: '2px'
            }}>
              v0.0.1
            </div>
          </div>
        </div>
        </div>
      </Sider>
      
      <Layout style={{ marginLeft: 220, marginTop: '64px' }}>
        <Content style={{ 
          padding: '20px', 
          background: '#f5f7fa',
          minHeight: 'calc(100vh - 184px)'
        }}>
          {!dbInitialized && (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <div>正在初始化数据库...</div>
            </div>
          )}

          {dbInitialized && (!status.isConnected || status.modelCount === 0 || getCurrentModelStatus() === 'error') && showAlert && !location.pathname.startsWith('/settings') && (
            <Alert
              message={
                !status.isConnected ? 'Ollama 服务未连接' : 
                status.modelCount === 0 ? '未检测到 AI 模型' :
                '模型暂未配置'
              }
              description={
                !status.isConnected 
                  ? '请确保 Ollama 服务正在运行。在终端中执行命令：ollama serve'
                  : status.modelCount === 0
                    ? '请先安装 AI 模型。在终端中执行命令：ollama pull qwen3:8b'
                    : '请前往配置页面选择并配置可用模型'
              }
              type={!status.isConnected ? 'error' : 'warning'}
              showIcon
              closable
              style={{ marginBottom: '16px' }}
              onClose={() => setShowAlert(false)}
              action={
                <button 
                  onClick={() => navigate('/settings/model')}
                  style={{ 
                    color: '#1890ff', 
                    textDecoration: 'none',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    padding: 0,
                    font: 'inherit'
                  }}
                >
                  前往配置
                </button>
              }
            />
          )}

          <div style={{ 
            background: 'white', 
            padding: '24px', 
            borderRadius: '12px',
            minHeight: 'calc(100vh - 264px)',
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)'
          }}>
            <Outlet />
          </div>
        </Content>
        
        <Footer style={{ 
          background: 'white', 
          borderTop: '1px solid #f0f0f0',
          padding: '8px 20px',
          position: 'fixed',
          bottom: 0,
          left: 220,
          right: 0,
          zIndex: 1000,
          height: '40px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          fontSize: '12px'
        }}>
          <Space size={20}>
            <Space size={6}>
              <span style={{ color: '#8c8c8c' }}>Ollama 状态:</span>
              <span style={{ 
                color: status.isConnected ? '#52c41a' : '#ff4d4f',
                fontWeight: 500
              }}>
                {status.isConnected ? '已连接' : '未连接'}
              </span>
            </Space>
            
            <Space size={6}>
              <span style={{ color: '#8c8c8c' }}>模型数量:</span>
              <span style={{ 
                color: status.modelCount > 0 ? '#52c41a' : '#faad14',
                fontWeight: 500
              }}>
                {status.modelCount} 个
              </span>
            </Space>
            
            <Space size={6}>
              <span style={{ color: '#8c8c8c' }}>当前模型:</span>
              <span style={{ 
                color: getCurrentModelStatus() === 'success' ? '#52c41a' : 
                      getCurrentModelStatus() === 'warning' ? '#faad14' : '#ff4d4f',
                fontWeight: 500,
                maxWidth: '300px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
              }}>
                {getCurrentModelInfo()}
              </span>
              {getCurrentModelStatus() === 'error' && (
                <button 
                  onClick={() => navigate('/settings/model')}
                  style={{
                    background: '#ff4d4f',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    padding: '2px 8px',
                    fontSize: '11px',
                    cursor: 'pointer',
                    marginLeft: '8px'
                  }}
                >
                  前往配置
                </button>
              )}
            </Space>
          </Space>
          
          <Button 
            type="text" 
            size="small"
            icon={<ReloadOutlined />}
            onClick={refreshModels}
            loading={status.isLoading}
            style={{ color: '#1890ff' }}
          >
            刷新状态
          </Button>
        </Footer>
      </Layout>
    </Layout>
  );
};

export default MainLayout;