import * as React from 'react';
import { Dropdown, MenuProps, Button } from 'antd';
import { CodeBracketsSquare, EditPencil, Trash, ShareIos, Star, BrightStar, Eye, Heart, Calendar, BadgeCheck, Building, Menu, ArrowRight } from 'iconoir-react';
import './index.scss';

export interface AppCardProps {
    // 基本信息
    id: string;
    name: string;
    description: string;
    icon?: string;
    iconImage?: string;
    iconBgColor?: 'blue' | 'indigo' | 'teal' | 'purple' | 'rose' | 'cyan' | 'amber' | 'green' | 'orange';
    
    // 创建者信息
    creator?: string;
    creatorId?: string;
    proName?: string;  // 项目名称
    
    // 标签和认证
    tags?: Array<{
        label: string;
        color: 'slate' | 'blue' | 'indigo' | 'teal' | 'purple' | 'rose' | 'cyan' | 'amber';
    }>;
    certification?: string;
    
    // 状态标识
    isHot?: boolean;
    status?: 'draft' | 'pending' | 'approved' | 'rejected';
    
    // 统计数据
    viewCount?: number;
    favoriteCount?: number;
    createTime?: string;
    
    // 其他信息
    department?: string;
    visible?: 'public' | 'private' | 'vip';
    appId?: string;
    isCollect?: boolean;
    isCreator?: boolean;

    // 显示控制
    showCreator?: boolean;
    showActions?: boolean;
    showCertification?: boolean;
    showTags?: boolean;
    showHot?: boolean;
    showViewCount?: boolean;
    showFavoriteCount?: boolean;
    showCreateTime?: boolean;
    showStatus?: boolean;
    showDepartment?: boolean;
    showVisible?: boolean;
    showOperations?: boolean;

    // 回调函数
    onPlay?: () => void;
    onShare?: () => void;
    onFavorite?: () => void;
    onEdit?: () => void;
    onDelete?: () => void;
    onView?: () => void;
    onApi?: () => void;
    onApiDirect?: () => void;  // API 调用（非创建者显示）
}

const AppCard: React.FC<AppCardProps> = (props) => {
    const {
        // 基本信息
        name,
        description,
        icon,
        iconImage,
        iconBgColor = 'blue',
        
        // 创建者信息
        creator,
        proName,
        
        // 标签和认证
        tags = [],
        certification,
        
        // 状态标识
        isHot,
        status,
        
        // 统计数据
        viewCount,
        favoriteCount,
        createTime,
        
        // 其他信息
        department,
        visible,
        isCollect = false,
        isCreator = false,
        
        // 显示控制
        showCreator = true,
        showActions = true,
        showCertification = true,
        showTags = true,
        showHot = true,
        showViewCount = false,
        showFavoriteCount = false,
        showCreateTime = false,
        showStatus = false,
        showDepartment = false,
        showVisible = false,
        showOperations = false,
        
        // 回调函数
        onShare,
        onFavorite,
        onEdit,
        onDelete,
        onView,
        onApi,
        onApiDirect,
    } = props;

    // 配置对象
    const statusConfig = {
        draft: { label: '草稿', color: '#9CA3AF' },
        pending: { label: '审核中', color: '#F59E0B' },
        approved: { label: '已通过', color: '#10B981' },
        rejected: { label: '已拒绝', color: '#EF4444' },
    };

    const visibleConfig = {
        public: { label: '公开', color: '#005D80' },
        private: { label: '私有', color: '#6B7280' },
        vip: { label: 'VIP', color: '#F59E0B' },
    };

    // 构建操作菜单项
    const operationItems: MenuProps['items'] = React.useMemo(() => {
        const items: any[] = [];
        
        if (onApi) {
            items.push({
                key: 'api',
                label: 'API 调用',
                icon: <CodeBracketsSquare width="16" height="16" />,
                onClick: () => onApi(),
            });
        }

        if (isCreator && onEdit) {
            items.push({
                key: 'edit',
                label: '编辑',
                icon: <EditPencil width="16" height="16" />,
                onClick: () => onEdit(),
            });
        }

        if (isCreator && onDelete) {
            items.push({
                key: 'delete',
                label: '删除',
                icon: <Trash width="16" height="16" />,
                danger: true,
                onClick: () => onDelete(),
            });
        }
        
        return items;
    }, [onApi, onEdit, onDelete, isCreator]);

    // 事件处理
    const handleShareClick = () => {
        onShare?.();
    };

    const handleFavoriteClick = () => {
        onFavorite?.();
    };

    const handleViewClick = () => {
        onView?.();
    };

    return (
        <div className='app-card'>
            {/* Hot 标签 */}
            {showHot && isHot && (
                <span className='card-hot-badge'>Hot</span>
            )}

            {/* 状态标签 */}
            {showStatus && status && (
                <span 
                    className='card-status-badge'
                    style={{ background: statusConfig[status].color }}
                >
                    {statusConfig[status].label}
                </span>
            )}

            {/* 操作按钮 - 悬停显示 */}
            {showActions && (
                <div className='card-actions'>
                    <button
                        className='card-action-btn'
                        onClick={(e) => {
                            e.stopPropagation();
                            handleShareClick();
                        }}
                        title='分享'
                    >
                        <ShareIos width="18" height="18" />
                    </button>
                    <button
                        className='card-action-btn'
                        onClick={(e) => {
                            e.stopPropagation();
                            handleFavoriteClick();
                        }}
                        title={isCollect ? '取消收藏' : '收藏'}
                    >
                        {isCollect ? (
                            <BrightStar width="18" height="18" style={{ color: '#F5E663' }} />
                        ) : (
                            <Star width="18" height="18" />
                        )}
                    </button>
                </div>
            )}

            {/* 卡片头部：图标 + 创建者信息 */}
            <div className='card-header'>
                <div className={`card-icon-wrapper bg-${iconBgColor}`}>
                    {iconImage ? (
                        <img alt={name} className='card-icon' src={iconImage} />
                    ) : icon ? (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 24, height: 24 }}>
                            {/* 动态 icon 支持 - 如果传入的是 iconoir 组件名称则渲染，否则显示占位 */}
                            <BrightStar width="24" height="24" />
                        </div>
                    ) : null}
                </div>

                {showCreator && creator && (
                    <div className='card-creator'>
                        <div className='card-creator-info'>
                            <span className='card-creator-label'>创建者</span>
                            <span className='card-creator-name'>{creator}</span>
                            {proName && (
                                <span className='card-pro-name' title={proName}>{proName}</span>
                            )}
                        </div>
                    </div>
                )}
            </div>

            {/* 应用名称 */}
            <h5 className='card-title'>{name}</h5>

            {/* 应用描述 */}
            <p className='card-description'>{description}</p>

            {/* 标签 */}
            {showTags && tags.length > 0 && (
                <div className='card-tags'>
                    {tags.map((tag, index) => (
                        <span key={index} className={`card-tag tag-${tag.color}`}>
                            {tag.label}
                        </span>
                    ))}
                </div>
            )}

            {/* 统计信息 */}
            {(showViewCount || showFavoriteCount || showCreateTime) && (
                <div className='card-meta'>
                    <div className='card-meta-left'>
                        {showViewCount && viewCount !== undefined && (
                            <span className='card-meta-item'>
                                <Eye width="14" height="14" />
                                <span>{viewCount}</span>
                            </span>
                        )}
                        {showFavoriteCount && favoriteCount !== undefined && (
                            <span className='card-meta-item'>
                                <Heart width="14" height="14" />
                                <span>{favoriteCount}</span>
                            </span>
                        )}
                    </div>
                    {showCreateTime && createTime && (
                        <div className='card-meta-right'>
                            <span className='card-meta-item'>
                                <Calendar width="14" height="14" />
                                <span>{createTime}</span>
                            </span>
                        </div>
                    )}
                </div>
            )}

            {/* 底部信息：认证/部门/可见性 */}
            {showCertification && (
                <div className='card-footer-info'>
                    {certification && (
                        <div className='card-certification'>
                            <BadgeCheck width="14" height="14" />
                            <span>{certification}</span>
                        </div>
                    )}
                    {showDepartment && department && (
                        <div className='card-department'>
                            <Building width="14" height="14" />
                            <span>{department}</span>
                        </div>
                    )}
                    {showVisible && visible && (
                        <span 
                            className='card-visible-tag'
                            style={{ color: visibleConfig[visible].color }}
                        >
                            {visibleConfig[visible].label}
                        </span>
                    )}
                </div>
            )}

            {/* 悬停操作按钮层 */}
            {showOperations && (
                <div className='card-hover-actions'>
                    {/* 创建者显示【更多操作】，非创建者显示【API 调用】 */}
                    {isCreator ? (
                        <Dropdown
                            menu={{ items: operationItems }}
                            trigger={['click']}
                            placement='topLeft'
                            className='card-operation-dropdown'
                        >
                            <Button
                                className='card-operation-btn'
                                icon={<Menu width="18" height="18" />}
                                size='large'
                            >
                                更多操作
                            </Button>
                        </Dropdown>
                    ) : (
                        <Button
                            className='card-operation-btn'
                            icon={<CodeBracketsSquare width="18" height="18" />}
                            size='large'
                            onClick={(e) => {
                                e.stopPropagation();
                                onApiDirect?.();
                            }}
                        >
                            API 调用
                        </Button>
                    )}

                    <Button
                        className='card-use-btn'
                        icon={<ArrowRight width="18" height="18" />}
                        size='large'
                        onClick={(e) => {
                            e.stopPropagation();
                            handleViewClick();
                        }}
                    >
                        立即使用
                    </Button>
                </div>
            )}
        </div>
    );
};

export default AppCard;
