import * as React from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { AppCard, GuideTips, FilterBar } from '@/components/common';
import { Pagination, message, Form, Button, Input } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import './style.scss';
// 导入全局 Mock 数据
import { getAppsByPageType, getPageConfig, processAppData, mockCurrentUser } from '@/mock';
// 导入 GuideTips 配置
import { getGuideTipsConfig } from '@/config/guideTips';
import Step1Drawer from '../form/Step1Drawer';
import { useQuestionAnswerFormStore } from '../form/store';

const QuestionAnswerList: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    
    // 使用表单 Store
    const {
        form,
        appTypeList,
        appVisibleList,
        appProjectList,
        isAppPro,
        visibleFlag,
        vipList,
        inputs,
        selectedIcon,
        previewBg,
        setAppTypeList,
        setAppVisibleList,
        setAppProjectList,
        setIsAppPro,
        setVisibleFlag,
        setVipList,
        setInputs,
        setSelectedIcon,
        setPreviewBg,
    } = useQuestionAnswerFormStore();

    const [formInstance] = Form.useForm();
    
    // 获取页面配置（我创建的应用）
    const pageConfig = getPageConfig('myApps');

    // Tab 状态和搜索 - 默认选中"我创建的"
    const [activeTab, setActiveTab] = React.useState('myApps'); // 'myApps' | 'maintainerApps'
    const [searchText, setSearchText] = React.useState('');
    const [loading, setLoading] = React.useState(false);

    // 获取应用数据（根据 TAB 选择）
    const getAppListByTab = (tab: string) => {
        if (tab === 'maintainerApps') {
            return getAppsByPageType('maintainerApps');
        } else {
            return getAppsByPageType('myApps');
        }
    };

    const [list, setList] = React.useState(getAppListByTab('myApps'));
    const [currentPage, setCurrentPage] = React.useState(1);
    const [pageSize, setPageSize] = React.useState(8);
    const [tipsCollapsed, setTipsCollapsed] = React.useState(true);
    const [drawerOpen, setDrawerOpen] = React.useState(false);

    // 监听 TAB 变化，更新数据
    React.useEffect(() => {
        setList(getAppListByTab(activeTab));
        setCurrentPage(1);  // 重置到第一页
    }, [activeTab]);

    // 监听路由状态，如果从 Step2 返回则自动打开 Drawer
    React.useEffect(() => {
        if (location.state?.openDrawer) {
            setDrawerOpen(true);
            // 清除状态，避免刷新后再次打开
            navigate(location.pathname, { replace: true, state: {} });
        }
    }, [location.state?.openDrawer]);

    const handlePlay = (appId: string) => {
        console.log('立即使用:', appId);
        navigate(`/appCenter/questionAnswer/modify?id=${appId}`);
    };

    const handleCreate = () => {
        setDrawerOpen(true);
    };

    const handleDrawerNext = async () => {
        try {
            await formInstance.validateFields(['name', 'desc', 'iconType']);
            setDrawerOpen(false);
            // 跳转到 create 路由，传递 fromList 状态
            navigate('/appCenter/questionAnswer/create', { state: { fromList: true } });
        } catch (error) {
            console.error('验证失败:', error);
        }
    };

    const handleApi = (appId: string) => {
        console.log('API 服务:', appId);
        message.info('API 文档功能开发中');
    };

    const handleEdit = (appId: string) => {
        console.log('编辑应用:', appId);
        navigate(`/appCenter/questionAnswer/modify?id=${appId}`);
    };

    const handleDelete = (appId: string) => {
        console.log('删除应用:', appId);
        message.info('删除功能开发中');
    };

    const handleShare = (appId: string) => {
        console.log('分享应用:', appId);
        message.info('分享功能开发中');
    };

    const handleFavorite = (appId: string) => {
        console.log('收藏应用:', appId);
        message.success('已收藏');
    };

    const handlePageChange = (page: number, size: number) => {
        setCurrentPage(page);
        setPageSize(size);
    };

    // 搜索处理
    const handleSearch = async () => {
        setLoading(true);
        // 模拟异步搜索
        await new Promise(resolve => setTimeout(resolve, 500));
        
        const allApps = getAppListByTab(activeTab);
        if (!searchText.trim()) {
            setList(allApps);
        } else {
            const filtered = allApps.filter(app =>
                app.name.toLowerCase().includes(searchText.toLowerCase()) ||
                app.description.toLowerCase().includes(searchText.toLowerCase())
            );
            setList(filtered);
        }
        setLoading(false);
        setCurrentPage(1);
    };

    // 分页
    const paginatedApps = list.slice((currentPage - 1) * pageSize, currentPage * pageSize);

    // 获取 GuideTips 配置
    const guideTipsConfig = getGuideTipsConfig('questionAnswer');

    return (
        <div className="page-container">
            {/* 标题区域 */}
            <div className="list-header with-tips">
                <div className='list-header-title'>
                    <h1>{pageConfig.title}</h1>
                    <p>{pageConfig.description}</p>
                </div>
                <div className='list-header-actions'>
                    <Button
                        type='primary'
                        icon={<PlusOutlined />}
                        onClick={() => setDrawerOpen(true)}
                    >
                        创建
                    </Button>
                </div>
            </div>

            {/* Tips 提示组件 */}
            {guideTipsConfig && (
                <GuideTips
                    visible={true}
                    title={guideTipsConfig.title}
                    steps={guideTipsConfig.steps}
                />
            )}

            {/* 筛选工具栏 - FilterBar 组件 */}
            <FilterBar
                tabs={[
                    { key: 'myApps', label: '我创建的' },
                    { key: 'maintainerApps', label: '我可以维护的' },
                ]}
                activeTab={activeTab}
                onTabChange={setActiveTab}
                searchPlaceholder="请输入 RAG 应用名称或描述进行搜索"
                searchValue={searchText}
                onSearchChange={setSearchText}
                onSearch={handleSearch}
                loading={loading}
                searchWidth={300}
            />

            <div className='app-card-grid'>
                {paginatedApps.map((app) => {
                    // 判断是否为创建者
                    const isCreator = app.creatorId === mockCurrentUser.id;

                    return (
                        <AppCard
                            key={app.id}
                            {...app}  // 直接使用原始数据，不使用 processAppData
                            isCreator={isCreator}
                            showCreator={pageConfig.showCreator}
                            showActions={true}  // 显示悬停操作按钮（分享/收藏）
                            showCertification={pageConfig.showCertification}
                            showTags={pageConfig.showTags}
                            showHot={pageConfig.showHot}
                            showViewCount={true}
                            showFavoriteCount={true}
                            showCreateTime={true}
                            createTime={app.createTime ? app.createTime.split(' ')[0] : ''}
                            showStatus={pageConfig.showStatus}
                            showVisible={pageConfig.showVisible}
                            showOperations={true}  // 显示悬停操作按钮
                            isCreator={isCreator}
                            onView={() => handlePlay(app.id)}
                            onApi={() => handleApi(app.id)}
                            onApiDirect={() => handleApi(app.id)}  // API 调用（非创建者）
                            onEdit={isCreator ? () => handleEdit(app.id) : undefined}
                            onDelete={isCreator ? () => handleDelete(app.id) : undefined}
                            onShare={() => handleShare(app.id)}
                            onFavorite={() => handleFavorite(app.id)}
                        />
                    );
                })}
            </div>

            {/* 分页器 */}
            <div className='pagination-container'>
                <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={list.length}
                    onChange={handlePageChange}
                    showSizeChanger={true}
                    showQuickJumper={true}
                    showTotal={(total) => `共 ${total} 个应用`}
                    pageSizeOptions={['8', '16', '24', '32']}
                />
            </div>

            {/* Step1 Drawer */}
            <Step1Drawer
                open={drawerOpen}
                onClose={() => setDrawerOpen(false)}
                form={formInstance}
                appTypeList={appTypeList}
                appVisibleList={appVisibleList}
                appProjectList={appProjectList}
                isAppPro={isAppPro}
                visibleFlag={visibleFlag}
                vipList={vipList}
                userInfo={mockCurrentUser}
                inputs={inputs}
                selectedIcon={selectedIcon}
                previewBg={previewBg}
                onAppChange={(typeId) => {
                    if (typeId === 62) setIsAppPro(true);
                    else setIsAppPro(false);
                }}
                onVisibleChange={setVisibleFlag}
                onRemoveVip={(userId) => setVipList(vipList.filter(item => item.userId !== userId))}
                onVipConfirm={setVipList}
                onNext={handleDrawerNext}
                onIconChange={setSelectedIcon}
                onBgColorChange={setPreviewBg}
                onInputsChange={setInputs}
            />
        </div>
    );
};

export default QuestionAnswerList;
