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

function TextFlowNode({ id, data, selected, type }) {
  const { getNodeHandles, patchNodeData, presets, savePreset } = useWorkflow();
  const handles = getNodeHandles(type, data);
  const runtime = data.runtime || {};
  const presetOptions = [...presets.default, ...presets.custom];
  const textareaHeight = Math.max((data.height || 210) - 104, 148);
  const editorText = data.text ?? '';

  const applyPreset = (presetId, event) => {
    const preset = presetOptions.find((item) => item.id === presetId);
    if (!preset) {
      return;
    }

    patchNodeData(id, { text: preset.text });
    if (event) {
      event.target.value = '';
    }
  };

  const handleSavePreset = async () => {
    const name = window.prompt('Preset name:');

    if (!name) {
      return;
    }

    await savePreset(name, editorText);
  };

  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">
        <div className="field-row">
          <select
            className="nodrag node-input"
            defaultValue=""
            onChange={(event) => applyPreset(event.target.value, event)}
          >
            <option value="">Выбрать</option>
            {presets.default.length > 0 ? <option disabled>Базовые пресеты</option> : null}
            {presets.default.map((preset) => (
              <option key={preset.id} value={preset.id}>
                {preset.name}
              </option>
            ))}
            {presets.custom.length > 0 ? <option disabled>Пользовательские пресеты</option> : null}
            {presets.custom.map((preset) => (
              <option key={preset.id} value={preset.id}>
                {preset.name}
              </option>
            ))}
          </select>

          <button type="button" className="nodrag node-button" onClick={handleSavePreset}>
            Сохранить
          </button>
        </div>

        <NodeDraftTextarea
          className="nodrag nowheel node-textarea node-textarea--inline is-editing"
          value={editorText}
          style={{ minHeight: `${textareaHeight}px` }}
          onCommit={(value) => patchNodeData(id, { text: value })}
        />

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

export default memo(TextFlowNode);
