import { memo } from 'react';
import NodeShell from '../components/NodeShell.jsx';
import { NodeDraftInput, NodeDraftTextarea } from '../components/NodeDraftField.jsx';
import { useWorkflow } from '../context/WorkflowContext.jsx';
import { getNodeAccent } from '../lib/nodeRegistry.js';

function ComponentFlowNode({ id, data, selected, type }) {
  const { getNodeHandles, patchNodeData, openComponent, saveComponentNode } = useWorkflow();
  const handles = getNodeHandles(type, data);
  const runtime = data.runtime || {};
  const subgraphNodes = (data.subgraph?.nodes || []).filter(
    (node) => !['system/component-input', 'system/component-output'].includes(node.type),
  );

  return (
    <NodeShell
      nodeId={id}
      title={data.title?.trim() || 'Компонент'}
      accent={getNodeAccent(type)}
      selected={selected}
      status={runtime.status}
      inputs={handles.inputs}
      outputs={handles.outputs}
    >
      <div className="field-stack">
        <NodeDraftInput
          className="nodrag node-input"
          type="text"
          value={data.title || ''}
          placeholder="Название компонента"
          onCommit={(value) => patchNodeData(id, { title: value })}
        />

        <NodeDraftTextarea
          className="nodrag nowheel node-textarea component-node__description"
          value={data.description || ''}
          placeholder="Короткое описание того, что происходит внутри"
          onCommit={(value) => patchNodeData(id, { description: value })}
        />

        <div className="component-node__meta">
          <span>Внутренних нод: {subgraphNodes.length}</span>
          <div className="button-row">
            <button type="button" className="nodrag node-button" onClick={() => saveComponentNode(id)}>
              Сохранить
            </button>
            <button type="button" className="nodrag node-button" onClick={() => openComponent(id)}>
              Открыть
            </button>
          </div>
        </div>

        {runtime.error ? <div className="node-error">{runtime.error}</div> : null}
      </div>
    </NodeShell>
  );
}

export default memo(ComponentFlowNode);
