import * as React from 'react';
import { Pagination } from 'antd';
import { AppCard, FilterDrawer, HeroBanner, StatsGrid } from '@/components/common';
import { useAppStore, type FilterState } from './store';
import './style.scss';
// 导入全局 Mock 数据
import { getAppsByPageType, getPageConfig, processAppData, mockCurrentUser } from '@/mock';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';

const AppPlazaList: React.FC = () => {
    const {
        filterOpen,
        setFilterOpen,
        selectedSort,
        setSelectedSort,
        category1,
        category2,
        sort,
        setFilters,
        currentPage,
        pageSize,
        setCurrentPage,
        setPageSize,
    } = useAppStore();

    // 组合 filters 对象
    const filters: FilterState = { category1, category2, sort };

    // 获取页面配置
    const pageConfig = getPageConfig('appPlaza');
    
    // 获取应用数据（使用全局 Mock）
    const allApps = getAppsByPageType('appPlaza');

    const handleApplyFilter = (newFilters: FilterState) => {
        setFilters(newFilters);
        setSelectedSort(newFilters.sort);
        setCurrentPage(1);
        console.log('应用筛选:', newFilters);
    };

    const handleSortChange = (sortType: string) => {
        setSelectedSort(sortType);
        setFilters({ sort: sortType });
    };

    // 根据筛选和分页处理数据
    const getFilteredAndPaginatedApps = () => {
        let filtered = [...allApps];

        // 根据排序筛选
        if (filters.sort === '最新上线') {
            filtered.sort((a, b) => b.id.localeCompare(a.id));
        } else if (filters.sort === '高频率调用') {
            // 模拟按热度排序（使用 viewCount）
            filtered.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));
        }

        // 分页
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        return filtered.slice(startIndex, endIndex);
    };

    const paginatedApps = getFilteredAndPaginatedApps();

    const navigate = useNavigate();

    const handlePlay = (appId: string) => {
        console.log('立即使用:', appId);
    };

    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);
    };

    return (
        <div className='app-plaza-list'>
            {/* Hero Banner - 建科 GPT-5.0 专业版广告 */}
            <HeroBanner />

            {/* 数据统计概览 */}
            <StatsGrid />

            {/* 筛选工具栏 */}
            <div className='list-header'>
                <div className='list-header-title'>
                    <h3>{pageConfig.title}</h3>
                    <p>{pageConfig.description}</p>
                </div>
                <div className='list-header-actions'>
                    <div className='sort-buttons'>
                        <button
                            className={`sort-btn ${selectedSort === '综合排序' ? 'active' : ''}`}
                            onClick={() => handleSortChange('综合排序')}
                        >
                            综合排序
                        </button>
                        <button
                            className={`sort-btn ${selectedSort === '最新上线' ? 'active' : ''}`}
                            onClick={() => handleSortChange('最新上线')}
                        >
                            最新上线
                        </button>
                        <button
                            className={`sort-btn ${selectedSort === '高频率调用' ? 'active' : ''}`}
                            onClick={() => handleSortChange('高频率调用')}
                        >
                            高频率调用
                        </button>
                    </div>
                    <button className='filter-btn' onClick={() => setFilterOpen(true)}>
                        <span className='iconify' data-icon='solar:filter-linear'></span>
                    </button>
                </div>
            </div>

            <div className='app-card-grid'>
                {paginatedApps.map((app) => {
                    return (
                        <AppCard
                            key={app.id}
                            {...app}  // 直接使用原始数据，不使用 processAppData
                            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] : ''}
                            showOperations={true}  // 显示悬停操作按钮
                            isCreator={app.creatorId === mockCurrentUser.id}
                            onView={() => handlePlay(app.id)}
                            onApi={() => handleApi(app.id)}
                            onApiDirect={() => handleApi(app.id)}  // API 调用（非创建者）
                            onEdit={app.creatorId === mockCurrentUser.id ? () => handleEdit(app.id) : undefined}
                            onDelete={app.creatorId === mockCurrentUser.id ? () => handleDelete(app.id) : undefined}
                            onShare={() => handleShare(app.id)}
                            onFavorite={() => handleFavorite(app.id)}
                        />
                    );
                })}
            </div>

            {/* 分页器 */}
            <div className='pagination-container'>
                <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={allApps.length}
                    onChange={handlePageChange}
                    showSizeChanger={true}
                    showQuickJumper={true}
                    showTotal={(total) => `共 ${total} 条`}
                    pageSizeOptions={['12', '24', '36', '48']}
                />
            </div>

            {/* 筛选抽屉 */}
            <FilterDrawer
                open={filterOpen}
                onClose={() => setFilterOpen(false)}
                onApplyFilter={handleApplyFilter}
            />
        </div>
    );
};

export default AppPlazaList;
