import React from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import type { FlowNodeData } from '../../types';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { isConfigurableNode } from '../types';

/**
 * BaseNode - shadcn/ui 风格节点
 * 参考 React Flow 官方设计 + shadcn 设计系统
 */
const BaseNode: React.FC<NodeProps> = ({ data, selected }) => {
    const nodeData = data as FlowNodeData;
    const definition = nodeData?.nodeDefinition;
    
    if (!definition) {
        return <div className="text-xs text-muted-foreground">节点未配置</div>;
    }
    
    const config = definition.renderConfig;
    
    // 条件评估函数
    const evaluateCondition = (currentValue: any, expectedValue: any, operator: string = '==='): boolean => {
        switch (operator) {
            case '===':
            case '==':
                return currentValue === expectedValue;
            case '!==':
            case '!=':
                return currentValue !== expectedValue;
            case '>':
                return Number(currentValue) > Number(expectedValue);
            case '<':
                return Number(currentValue) < Number(expectedValue);
            case '>=':
                return Number(currentValue) >= Number(expectedValue);
            case '<=':
                return Number(currentValue) <= Number(expectedValue);
            case 'includes':
                return Array.isArray(currentValue) && currentValue.includes(expectedValue);
            case 'notIncludes':
                return Array.isArray(currentValue) && !currentValue.includes(expectedValue);
            case 'in':
                return Array.isArray(expectedValue) && expectedValue.includes(currentValue);
            default:
                return currentValue === expectedValue;
        }
    };

    // 渲染输入字段标签（来自 inputMappingSchema）
    const renderInputSection = () => {
        if (!isConfigurableNode(definition) || !definition.inputMappingSchema) {
            return null;
        }
        
        const schema = definition.inputMappingSchema;
        const inputMapping = nodeData.inputMapping || {};
        
        // 获取所有定义的输入字段（从 schema）
        if (!schema.properties) {
            return null;
        }
        
        // 获取必填字段列表
        const requiredFields = Array.isArray(schema.required) ? schema.required : [];
        
        const allInputs = Object.keys(schema.properties)
            .map(key => {
                const fieldSchema = schema.properties![key];
                const fieldValue = inputMapping[key];
                
                // ✅ 检查 x-condition（字段是否应该显示）
                if (fieldSchema['x-condition']) {
                    const condition = fieldSchema['x-condition'];
                    const conditionField = condition.field;
                    const conditionValue = condition.value;
                    const conditionOperator = condition.operator || '===';
                    const currentFieldValue = inputMapping[conditionField];
                    
                    // 如果条件不满足，跳过该字段
                    if (!evaluateCondition(currentFieldValue, conditionValue, conditionOperator)) {
                        return null;
                    }
                }
                
                // 检查字段是否已填写（非空、非null、非undefined、非空字符串、非空数组）
                const isFilled = fieldValue !== undefined && 
                                fieldValue !== null && 
                                fieldValue !== '' &&
                                !(Array.isArray(fieldValue) && fieldValue.length === 0) &&
                                (typeof fieldValue !== 'number' || !isNaN(fieldValue));
                
                // 检查是否为必填字段
                const isRequired = requiredFields.includes(key);
                
                return {
                    key,
                    title: fieldSchema.title || key,
                    description: fieldSchema.description,
                    isFilled,
                    isRequired,
                };
            })
            .filter((input): input is NonNullable<typeof input> => input !== null);  // 过滤掉条件不满足的字段
        
        if (allInputs.length === 0) {
            return null;
        }
        
        return (
            <div className="space-y-2">
                {/* 输入标签 - 靠左 */}
                <div className="text-xs text-muted-foreground font-medium">输入</div>
                {/* 输入字段标签 */}
                <div className="flex flex-wrap gap-1.5">
                    {allInputs.map((input, index) => {
                        // 🎨 三色系统：
                        // 🟢 绿色：已填写
                        // 🔴 红色：必填但未填写
                        // ⚪ 灰色：非必填且未填写
                        let colorClass = '';
                        let statusIcon = '';
                        let statusText = '';
                        
                        if (input.isFilled) {
                            // 已填写 → 绿色
                            colorClass = 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300';
                            statusIcon = '✓';
                            statusText = '已填写';
                        } else if (input.isRequired) {
                            // 必填但未填写 → 红色
                            colorClass = 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300';
                            statusIcon = '✗';
                            statusText = '必填，未填写';
                        } else {
                            // 非必填且未填写 → 灰色
                            colorClass = 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400';
                            statusIcon = '○';
                            statusText = '可选，未填写';
                        }
                        
                        return (
                            <span 
                                key={index}
                                className={`
                                    text-xs px-2 py-1 rounded-md font-medium inline-flex items-center
                                    ${colorClass}
                                `}
                                title={`${input.description} ${statusIcon} ${statusText}`}
                            >
                                {input.title}
                            </span>
                        );
                    })}
                </div>
            </div>
        );
    };
    
    // 渲染输出字段标签
    const renderOutputSection = () => {
        if (!nodeData.outputs || nodeData.outputs.length === 0) {
            return null;
        }
        return (
            <div className="space-y-2">
                {/* 输出标签 - 靠左 */}
                <div className="text-xs text-muted-foreground font-medium">输出</div>
                {/* 输出字段标签 */}
                <div className="flex flex-wrap gap-1.5">
                    {nodeData.outputs.map((output, index) => (
                        <span 
                            key={index}
                            className="text-xs px-2 py-1 bg-secondary text-secondary-foreground rounded-md font-medium inline-flex items-center"
                            title={output.description}
                        >
                            {output.title || output.name}
                        </span>
                    ))}
                </div>
            </div>
        );
    };

    // 图标容器 - shadcn 风格
    const renderIcon = () => {
        if (config.icon.type === 'emoji') {
            return (
                <div 
                    className="
                        flex items-center justify-center
                        rounded-lg
                        transition-all duration-200
                        group-hover:scale-105
                        flex-shrink-0
                        shadow-sm
                    "
                    style={{
                        width: '36px',
                        height: '36px',
                        background: `linear-gradient(135deg, ${config.theme.primary}, ${config.theme.secondary})`,
                    }}
                >
                    <span 
                        className="text-white text-lg leading-none"
                    >
                        {config.icon.content}
                    </span>
                </div>
            );
        }
        return null;
    };
    
    // shadcn 风格连接点
    const handleClass = `
        !w-3 !h-3 !rounded-full !border-2 !border-background
        transition-all duration-200
        hover:!w-3.5 hover:!h-3.5 hover:!shadow-md
    `;
    
    const getHandleStyle = () => ({
        background: config.theme.primary,
    });
    
    // 配置徽章 - shadcn badge 风格
    const renderBadge = () => {
        if (!config.features.showBadge) return null;
        if (!nodeData.configs || Object.keys(nodeData.configs).length <= 3) return null;
        
        return (
            <div 
                className="
                    absolute -top-1.5 -right-1.5
                    inline-flex items-center justify-center
                    w-4 h-4 rounded-full
                    bg-primary text-primary-foreground
                    text-[9px] font-semibold
                    border-2 border-background
                    shadow-sm
                "
            >
                ✓
            </div>
        );
    };
    
    // 椭圆形节点（开始/结束）使用特殊布局
    const isEllipse = config.shape === 'ellipse';
    
    return (
        <div className="group relative">
            {/* 输入连接点 */}
            {config.handles.input && (
                <Handle
                    type="target"
                    position={Position.Left}
                    className={handleClass}
                    style={getHandleStyle()}
                />
            )}
            
            {/* 使用 shadcn Card 组件 */}
            <Card 
                className={`
                    ${isEllipse ? 'rounded-full px-6 py-3' : 'min-w-[240px] max-w-[420px]'}
                    ${selected ? 'ring-2 ring-primary ring-offset-2 ring-offset-background' : ''}
                    transition-all duration-200
                    hover:shadow-lg hover:border-primary/50
                `}
            >
                {isEllipse ? (
                    // 椭圆形节点：紧凑布局，图标+文字居中
                    <div className="flex items-center justify-center gap-3 px-2">
                        {renderIcon()}
                        <span className="text-sm font-semibold whitespace-nowrap">
                            {nodeData.label || definition.nodeName}
                        </span>
                    </div>
                ) : (
                    // 普通节点：使用 Card 的标准布局
                    <>
                        <CardHeader className="pb-3">
                            {/* 图标 + 标题 */}
                            <div className="flex items-center gap-3">
                                {renderIcon()}
                                <CardTitle className="text-base">
                                    {nodeData.label || definition.nodeName}
                                </CardTitle>
                            </div>
                        </CardHeader>
                        
                        {/* 输入/输出部分 */}
                        {(renderInputSection() || renderOutputSection()) && (
                            <CardContent className="pt-0 space-y-3">
                                {/* 输入部分 */}
                                {renderInputSection()}
                                
                                {/* 输出部分 */}
                                {renderOutputSection()}
                            </CardContent>
                        )}
                    </>
                )}
            </Card>
            
            {/* 输出连接点 */}
            {config.handles.output && (
                <Handle
                    type="source"
                    position={Position.Right}
                    className={handleClass}
                    style={getHandleStyle()}
                />
            )}
            
            {/* 配置徽章 */}
            {renderBadge()}
        </div>
    );
};

export default React.memo(BaseNode);
