/**
 * Automation2 Flow Editor - Field that supports node reference only (no static value).
 */

import React, { useState } from 'react';
import {
  isRef,
  createValue,
  formatRefLabel,
  type DataRef,
} from './dataRef';
import { RefSourceSelect } from './RefSourceSelect';
import { DataPicker } from './DataPicker';
import { useAutomation2DataFlow } from '../../context/Automation2DataFlowContext';
import styles from '../../editor/Automation2FlowEditor.module.css';

export type FieldType = 'textarea' | 'input';

interface DynamicValueFieldProps {
  paramKey: string;
  value: unknown;
  onChange: (key: string, value: unknown) => void;
  label: string;
  fieldType?: FieldType;
  placeholder?: string;
  rows?: number;
  /** Inline dropdown instead of popup picker */
  variant?: 'picker' | 'dropdown';
}

export const DynamicValueField: React.FC<DynamicValueFieldProps> = ({
  paramKey,
  value,
  onChange,
  label,
  placeholder,
  variant = 'picker',
}) => {
  const dataFlow = useAutomation2DataFlow();
  const [pickerOpen, setPickerOpen] = useState(false);

  const ref: DataRef | null = isRef(value) ? value : null;
  const availableIds = dataFlow?.getAvailableSourceIds() ?? [];
  const hasUsefulSources = availableIds.some((id) => {
    const n = dataFlow?.nodes.find((x) => x.id === id);
    return n?.type !== 'trigger.manual';
  });
  const canUseRef = dataFlow !== null && hasUsefulSources;

  const handleSetRef = (newRef: DataRef | null) => {
    onChange(paramKey, newRef ?? createValue(''));
  };

  if (!canUseRef) {
    return (
      <div className={styles.dynamicValueField}>
        <label>{label}</label>
        <p className={styles.dynamicValueEmptyHint}>Keine vorherigen Nodes verfügbar.</p>
      </div>
    );
  }

  if (variant === 'dropdown') {
    return (
      <div className={styles.dynamicValueField}>
        <label>{label}</label>
        <RefSourceSelect
          value={ref}
          onChange={handleSetRef}
          placeholder={placeholder ?? label}
        />
      </div>
    );
  }

  return (
    <div className={styles.dynamicValueField}>
      <label>{label}</label>
      <div className={styles.dynamicValueRefDisplay}>
        <span className={styles.dynamicValueRefLabel}>
          {ref
            ? formatRefLabel(
                ref,
                dataFlow?.nodes ?? [],
                (nid) => dataFlow?.nodes.find((n) => n.id === nid)?.title ?? nid
              )
            : '—'}
        </span>
        <button
          type="button"
          className={styles.dynamicValuePickBtn}
          onClick={() => setPickerOpen(true)}
        >
          Wählen…
        </button>
      </div>

      {dataFlow && (
        <DataPicker
          open={pickerOpen}
          onClose={() => setPickerOpen(false)}
          onPick={(r) => {
            handleSetRef(r);
            setPickerOpen(false);
          }}
          availableSourceIds={dataFlow.getAvailableSourceIds()}
          nodes={dataFlow.nodes}
          nodeOutputsPreview={dataFlow.nodeOutputsPreview}
          getNodeLabel={dataFlow.getNodeLabel}
        />
      )}
    </div>
  );
};
