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.less';

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 handleApplyFilter = (newFilters: FilterState) => {
        setFilters(newFilters);
        setSelectedSort(newFilters.sort);
        setCurrentPage(1);
        console.log('应用筛选:', newFilters);
    };

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

    const handlePageChange = (page: number, size: number) => {
        setCurrentPage(page);
        setPageSize(size);
        console.log('分页变化:', page, size);
    };

    const apps = [
        {
            id: 'app001',
            name: '智审助手 Pro',
            description: '自动化公文审查、错别字纠正及语义合规性实时预警系统。',
            icon: 'solar:document-text-linear',
            iconBgColor: 'blue' as const,
            tags: [
                { label: 'NLP', color: 'slate' as const },
                { label: '私有部署', color: 'blue' as const },
            ],
            certification: '信创一级认证',
        },
        {
            id: 'app002',
            name: '视觉政务预警',
            description: '针对政务服务中心的窗口行为分析与人流密度实时监测。',
            icon: 'solar:mask-happly-bold-duotone',
            iconBgColor: 'indigo' as const,
            tags: [
                { label: 'CV', color: 'slate' as const },
                { label: '安防', color: 'indigo' as const },
            ],
            certification: '二级审计',
            isHot: true,
        },
        {
            id: 'app003',
            name: '经济态势分析仪',
            description: '多部门数据聚合，通过 AI 预测宏观经济指标走势。',
            icon: 'solar:chart-line-up-bold-duotone',
            iconBgColor: 'teal' as const,
            tags: [
                { label: 'Big Data', color: 'slate' as const },
                { label: '决策', color: 'teal' as const },
            ],
            certification: '省级认证',
        },
        {
            id: 'app004',
            name: '政策语义智译',
            description: '将晦涩的政策公文转化为通俗易懂的惠民说明。',
            icon: 'solar:translation-2-bold-duotone',
            iconBgColor: 'purple' as const,
            tags: [
                { label: 'LLM', color: 'slate' as const },
                { label: '惠民', color: 'purple' as const },
            ],
            certification: '国产化适配',
        },
        {
            id: 'app005',
            name: '权限行为内审',
            description: '基于 AI 的行为审计，识别并拦截异常数据访问行为。',
            icon: 'solar:key-minimalistic-square-bold-duotone',
            iconBgColor: 'rose' as const,
            tags: [
                { label: '安全', color: 'rose' as const },
            ],
            certification: '等保三级认证',
        },
        {
            id: 'app006',
            name: '12345 智播报',
            description: '语音政务热线智能分类与处理进度实时可视化。',
            icon: 'solar:user-speak-rounded-bold-duotone',
            iconBgColor: 'cyan' as const,
            tags: [
                { label: '语音', color: 'cyan' as const },
            ],
            certification: '内网可用',
        },
        {
            id: 'app007',
            name: '法条案例检索云',
            description: '关联解析法律条文，快速定位同类判决参考案例。',
            icon: 'solar:square-academic-cap-bold-duotone',
            iconBgColor: 'amber' as const,
            tags: [
                { label: '法律', color: 'amber' as const },
            ],
            certification: '高度合规',
        },
        {
            id: 'app008',
            name: '智能客服助手',
            description: '为企业提供 24/7 智能客服问答服务，支持多轮对话。',
            icon: 'solar:headphones-square-bold-duotone',
            iconBgColor: 'blue' as const,
            tags: [
                { label: 'NLP', color: 'slate' as const },
                { label: '客服', color: 'blue' as const },
            ],
            certification: '企业级认证',
        },
    ];

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

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

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

    const paginatedApps = getFilteredAndPaginatedApps();

    const handlePlay = (appId: string) => {
        console.log('播放应用:', appId);
    };

    const handleShare = (appId: string) => {
        console.log('分享应用:', appId);
    };

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

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

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

            {/* 筛选工具栏 */}
            <div className='filter-bar'>
                <div className='filter-bar-title'>
                    <h3>全部RAG推荐</h3>
                    <p>根据您的常用部门与岗位职责为您推荐</p>
                </div>
                <div className='filter-bar-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) => (
                    <AppCard
                        key={app.id}
                        {...app}
                        onPlay={() => handlePlay(app.id)}
                        onShare={() => handleShare(app.id)}
                        onFavorite={() => handleFavorite(app.id)}
                    />
                ))}
            </div>

            {/* 分页器 */}
            <div className='pagination-container'>
                <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={apps.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;
