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 SaveMemoryFlowNode({ id, data, selected, type }) {
  const { getNodeHandles, patchNodeData } = useWorkflow();
  const handles = getNodeHandles(type, data);
  const runtime = data.runtime || {};
  const hasSavedValue = runtime.value !== undefined && runtime.value !== null && runtime.value !== '';

  return (
    <NodeShell
      nodeId={id}
      title={data.title}
      accent={getNodeAccent(type)}
      selected={selected}
      status={runtime.status}
      inputs={handles.inputs}
      outputs={handles.outputs}
    >
      <div className="field-stack">
        <label className="field-stack">
          <span className="field-label">Ключ памяти</span>
          <NodeDraftInput
            className="nodrag node-input"
            value={data.key || ''}
            placeholder="name"
            onCommit={(value) => patchNodeData(id, { key: value })}
          />
        </label>

        <label className="field-stack">
          <span className="field-label">Инструкция извлечения</span>
          <NodeDraftTextarea
            className="nodrag nowheel node-textarea"
            value={data.instruction || ''}
            placeholder="Например: выбери значение из списка {text}"
            style={{ minHeight: '74px' }}
            onCommit={(value) => patchNodeData(id, { instruction: value })}
          />
        </label>

        <label className="field-row semantic-branch__retry-toggle">
          <input
            className="nodrag"
            type="checkbox"
            checked={data.retryOnUnclear !== false}
            onChange={(event) => patchNodeData(id, { retryOnUnclear: event.target.checked })}
          />
          <span>Переспрашивать при unclear</span>
        </label>

        {data.retryOnUnclear !== false ? (
          <>
            <NodeDraftTextarea
              className="nodrag nowheel node-textarea"
              value={data.retryQuestion || ''}
              placeholder="Вопрос для повтора..."
              style={{ minHeight: '70px' }}
              onCommit={(value) => patchNodeData(id, { retryQuestion: value })}
            />
            <label className="field-row">
              <input
                className="nodrag"
                type="checkbox"
                checked={Boolean(data.retryParaphrase)}
                onChange={(event) => patchNodeData(id, { retryParaphrase: event.target.checked })}
              />
              <span>Перефразировать unclear-вопрос</span>
            </label>
          </>
        ) : null}

        <div className="node-note">
          {hasSavedValue
            ? `Сохранено {${data.key}} = ${runtime.value}`
            : runtime.matchId === 'unclear'
              ? 'Извлечение: unclear'
            : 'Извлекает значение из ответа. Используйте {text} в инструкции для динамического входа.'}
        </div>

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

export default memo(SaveMemoryFlowNode);
