import * as React from 'react';
import { Pagination } from 'antd';
import { useLocation } from 'react-router-dom';
import { AppCard, FilterDrawer } from '@/components/common';
import { useCategoryAppStore, type FilterState } from './store';
import './style.less';

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 professionalApps = [
        {
            id: 'prof001',
            name: '法律智能咨询',
            description: '基于 AI 的法律条文解读和案例推荐系统。',
            icon: 'solar:scale-bold-duotone',
            iconBgColor: 'blue' as const,
            tags: [
                { label: '法律', color: 'blue' as const },
                { label: '专业', color: 'slate' as const },
            ],
            certification: '专业认证',
        },
        {
            id: 'prof002',
            name: '医疗诊断辅助',
            description: 'AI 辅助医疗诊断，提供专业医学建议。',
            icon: 'solar:heart-pulse-bold-duotone',
            iconBgColor: 'rose' as const,
            tags: [
                { label: '医疗', color: 'rose' as const },
                { label: '专业', color: 'slate' as const },
            ],
            certification: '医疗认证',
        },
        {
            id: 'prof003',
            name: '财务分析专家',
            description: '企业财务数据分析与风险评估系统。',
            icon: 'solar:graph-up-bold-duotone',
            iconBgColor: 'green' as const,
            tags: [
                { label: '财务', color: 'green' as const },
                { label: '专业', color: 'slate' as const },
            ],
            certification: '财务认证',
        },
        {
            id: 'prof004',
            name: '工程技术顾问',
            description: '工程技术问题智能解答与方案设计。',
            icon: 'solar:engineering-bold-duotone',
            iconBgColor: 'indigo' as const,
            tags: [
                { label: '工程', color: 'indigo' as const },
                { label: '专业', color: 'slate' as const },
            ],
            certification: '工程认证',
        },
    ];

    // 职能管理分类的应用
    const functionalApps = [
        {
            id: 'func001',
            name: '人力资源管理系统',
            description: '员工信息、考勤、绩效一体化管理。',
            icon: 'solar:users-group-rounded-bold-duotone',
            iconBgColor: 'blue' as const,
            tags: [
                { label: 'HR', color: 'blue' as const },
                { label: '管理', color: 'slate' as const },
            ],
            certification: '企业级认证',
        },
        {
            id: 'func002',
            name: '行政审批系统',
            description: '企业内部行政审批流程自动化。',
            icon: 'solar:clipboard-check-bold-duotone',
            iconBgColor: 'green' as const,
            tags: [
                { label: '行政', color: 'green' as const },
                { label: '管理', color: 'slate' as const },
            ],
            certification: '安全认证',
        },
        {
            id: 'func003',
            name: '采购管理平台',
            description: '企业采购流程管理与供应商管理。',
            icon: 'solar:cart-large-1-bold-duotone',
            iconBgColor: 'orange' as const,
            tags: [
                { label: '采购', color: 'orange' as const },
                { label: '管理', color: 'slate' as const },
            ],
            certification: '企业认证',
        },
    ];

    // 项目级应用分类的应用
    const projectApps = [
        {
            id: 'proj001',
            name: '智慧园区管理',
            description: '园区安防、能耗、设备一体化管理。',
            icon: 'solar:building-bold-duotone',
            iconBgColor: 'blue' as const,
            tags: [
                { label: '园区', color: 'blue' as const },
                { label: '项目', color: 'slate' as const },
            ],
            certification: '项目认证',
        },
        {
            id: 'proj002',
            name: '工程项目管理',
            description: '工程进度、质量、安全全方位管理。',
            icon: 'solar:hammer-bold-duotone',
            iconBgColor: 'amber' as const,
            tags: [
                { label: '工程', color: 'amber' as const },
                { label: '项目', color: 'slate' as const },
            ],
            certification: '工程认证',
        },
        {
            id: 'proj003',
            name: '研发项目管理',
            description: '研发项目进度、资源、文档管理。',
            icon: 'solar:code-square-bold-duotone',
            iconBgColor: 'purple' as const,
            tags: [
                { label: '研发', color: 'purple' as const },
                { label: '项目', color: 'slate' as const },
            ],
            certification: '研发认证',
        },
    ];

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

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

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

    const getAppsByCategory = () => {
        switch (category) {
            case 'professional':
                return professionalApps;
            case 'functional':
                return functionalApps;
            case 'project':
                return projectApps;
            default:
                return professionalApps;
        }
    };

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

    const apps = getAppsByCategory();
    const title = getCategoryTitle();

    // 根据筛选和分页处理数据
    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 handlePageChange = (page: number, size: number) => {
        setCurrentPage(page);
        setPageSize(size);
    };

    return (
        <div className='category-apps-list'>
            <div className='filter-bar'>
                <div className='filter-bar-title'>
                    <h3>{title}</h3>
                    <p>{category === 'professional' ? '专业知识类 RAG 应用' : category === 'functional' ? '职能管理类 RAG 应用' : '项目级 RAG 应用'}</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 CategoryAppsList;
