import React, { useContext, useMemo } from 'react'
import FlowContext from '../../lib/flowContext'
import { ArrowDownLeft, ArrowUpRight } from 'lucide-react'

const NODE_HAS_INPUT: Record<string, boolean> = {
    config: true,
    function: true,
    render: true,
    variable: false,
}
const NODE_HAS_OUTPUT: Record<string, boolean> = {
    config: true,
    function: true,
    render: true,
    variable: true,
}

type Props = {
    nodeId: string
    nodeType: 'config' | 'function' | 'render' | 'variable'
    children?: React.ReactNode
}

export function NodeFooterEdgeIndicators({ nodeId, nodeType, children }: Props) {
    const ctx = useContext(FlowContext)
    const edges = ctx?.edges ?? []

    const { inputs, outputs } = useMemo(() => {
        let inputs = 0
        let outputs = 0
        for (const e of edges) {
            if (e.target === nodeId) inputs += 1
            if (e.source === nodeId) outputs += 1
        }
        return { inputs, outputs }
    }, [edges, nodeId])

    const showInput = NODE_HAS_INPUT[nodeType] ?? false
    const showOutput = NODE_HAS_OUTPUT[nodeType] ?? false

    return (
        <div className="flex items-center gap-2 w-full text-xs text-muted-foreground">
            {showInput && (
                <span className="flex items-center gap-1 shrink-0" title="Input connections">
                    <ArrowDownLeft className="size-3.5" />
                    <span>{inputs}</span>
                </span>
            )}
            {showOutput && (
                <span className="flex items-center gap-1 shrink-0" title="Output connections">
                    <ArrowUpRight className="size-3.5" />
                    <span>{outputs}</span>
                </span>
            )}
            {children != null && (
                <>
                    {(showInput || showOutput) && <span className="shrink-0">|</span>}
                    <span className="min-w-0 truncate">{children}</span>
                </>
            )}
        </div>
    )
}
