import * as React from 'react';
import { Button, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import GuideTips from '../GuideTips';

interface TipsStep {
    title: string;
    description: string;
    stepNumber: number;
}

interface PageLayoutProps {
    // 标题区域
    showHeader?: boolean;
    pageTitle?: string;
    pageDescription?: string;
    showCreateButton?: boolean;  // 手动控制（优先级最高）
    onCreateClick?: () => void;
    createButtonText?: string;

    // Tips 组件
    showTips?: boolean;
    tipsTitle?: string;
    tipsSteps?: TipsStep[];

    // 立即创建模块
    showCreateAction?: boolean;
    onCreateActionClick?: () => void;
    createActionText?: string;

    // 筛选操作区域
    showOperation?: boolean;
    operationContent?: React.ReactNode;

    // 内容区域
    children: React.ReactNode;
    contentClassName?: string;
    showContentContainer?: boolean;  // 是否使用 .list-content 容器（默认 true，保持向后兼容）
}

/**
 * 全局页面布局组件
 * 统一管理 Main 区域的布局结构
 * 支持根据路由智能识别是否显示创建按钮
 */
const PageLayout: React.FC<PageLayoutProps> = (props) => {
    const location = useLocation();
    const navigate = useNavigate();
    
    const {
        showHeader = false,
        pageTitle = '',
        pageDescription = '',
        showCreateButton,  // 手动控制（优先级最高）
        onCreateClick,
        createButtonText = '创建',
        showTips = false,
        tipsTitle = '',
        tipsSteps = [],
        showCreateAction = false,
        onCreateActionClick,
        createActionText = '立即创建',
        showOperation = false,
        operationContent,
        children,
        contentClassName,
        showContentContainer = true,  // 默认使用 .list-content 容器
    } = props;

    // 智能识别是否显示创建按钮（根据路由）
    const shouldShowCreateButton = React.useMemo(() => {
        // 1. 如果手动指定了 showCreateButton，优先使用手动值
        if (showCreateButton !== undefined) {
            return showCreateButton;
        }
        
        // 2. 根据路由自动识别
        const createRoutes = [
            '/knowledge/knowledgeLib',  // 知识库管理
            '/appCenter/questionAnswer',  // 我创建的应用
        ];
        
        return createRoutes.some(route => location.pathname.startsWith(route));
    }, [showCreateButton, location.pathname]);

    // 智能识别创建按钮点击事件
    const handleCreateClick = React.useCallback(() => {
        if (onCreateClick) {
            onCreateClick();
        } else {
            // 根据路由自动跳转
            if (location.pathname.startsWith('/knowledge/knowledgeLib')) {
                // 触发知识库创建事件
                window.dispatchEvent(new CustomEvent('knowledgeLibCreate'));
            } else if (location.pathname.startsWith('/appCenter/questionAnswer')) {
                navigate('/appCenter/questionAnswer/create');
            }
        }
    }, [onCreateClick, location.pathname, navigate]);

    // 智能识别立即创建按钮点击事件
    const handleCreateActionClick = React.useCallback(() => {
        if (onCreateActionClick) {
            onCreateActionClick();
        } else {
            // 根据路由自动跳转
            if (location.pathname.startsWith('/knowledge/knowledgeLib')) {
                window.dispatchEvent(new CustomEvent('knowledgeLibCreate'));
            } else if (location.pathname.startsWith('/appCenter/questionAnswer')) {
                navigate('/appCenter/questionAnswer/create');
            }
        }
    }, [onCreateActionClick, location.pathname, navigate]);

    return (
        <div className='page-layout'>
            {/* 标题区域 */}
            {showHeader && (
                <div className={`list-header ${showTips ? 'with-tips' : ''}`}>
                    <div className='list-header-title'>
                        <h1>{pageTitle}</h1>
                        <p>{pageDescription}</p>
                    </div>
                    {shouldShowCreateButton && (
                        <div className='list-header-actions'>
                            <Button
                                type='primary'
                                icon={<PlusOutlined />}
                                onClick={handleCreateClick}
                            >
                                {createButtonText}
                            </Button>
                        </div>
                    )}
                </div>
            )}

            {/* Tips 提示组件 */}
            {showTips && tipsSteps.length > 0 && (
                <GuideTips
                    visible={true}
                    title={tipsTitle}
                    steps={tipsSteps}
                />
            )}

            {/* 立即创建模块 */}
            {showCreateAction !== false && shouldShowCreateButton && (
                <div className='create-action-wrapper'>
                    <Space>
                        <Button
                            type='primary'
                            icon={<PlusOutlined />}
                            size='large'
                            onClick={handleCreateActionClick}
                        >
                            {createActionText}
                        </Button>
                    </Space>
                </div>
            )}

            {/* 筛选操作区域 */}
            {showOperation && operationContent && (
                <div className='list-operation'>
                    {operationContent}
                </div>
            )}

            {/* 内容区域 */}
            {showContentContainer ? (
                <div className={`list-content ${contentClassName || ''}`}>
                    {children}
                </div>
            ) : (
                <div className={contentClassName}>
                    {children}
                </div>
            )}
        </div>
    );
};

export default PageLayout;
