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

const CategoryAppsList: React.FC = () => {
    const location = useLocation();
    const [category, setCategory] = React.useState<string>('professional');

    const {
        filterOpen,
        setFilterOpen,
        selectedSort,
        setSelectedSort,
        category1,
        category2,
        sort,
        setFilters,
        currentPage,
        pageSize,
        setCurrentPage,
        setPageSize,
    } = useCategoryAppStore();

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

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

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

    React.useEffect(() => {
        const params = new URLSearchParams(location.search);
        const cat = params.get('category') || 'professional';
        setCategory(cat);
    }, [location.search]);

    // 根据分类获取对应的页面类型和配置
    const getPageTypeByCategory = (): 'professional' | 'functional' | 'project' => {
        switch (category) {
            case 'functional':
                return 'functional';
            case 'project':
                return 'project';
            default:
                return 'professional';
        }
    };

    const pageType = getPageTypeByCategory();
    const pageConfig = getPageConfig(pageType);
    
    // 获取应用数据（使用全局 Mock）
    const allApps = getAppsByPageType(pageType);

    const getCategoryTitle = () => {
        switch (category) {
            case 'professional':
                return '专业知识';
            case 'functional':
                return '职能管理';
            case 'project':
                return '项目级应用';
            default:
                return '应用列表';
        }
    };

    const title = getCategoryTitle();

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

        // 根据排序筛选
        if (filters.sort === '最新上线') {
            filtered.sort((a, b) => b.id.localeCompare(a.id));
        } else if (filters.sort === '高频率调用') {
            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 handlePageChange = (page: number, size: number) => {
        setCurrentPage(page);
        setPageSize(size);
    };

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

    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('已收藏');
    };

    return (
        <div className='category-apps-list'>
            <div className='list-header'>
                <div className='list-header-title'>
                    <h1>{title}</h1>
                    <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)}>
                        <Filter size={18} />
                    </button>
                </div>
            </div>

            <div className='app-card-grid'>
                {paginatedApps.map((app) => {
                    const isCreator = app.creatorId === mockCurrentUser.id;

                    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={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={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 CategoryAppsList;
