/**
 * If/Else node config - inline UI: source dropdown, operator (type-dependent), value.
 * Kein Popup, alles in einer Zeile.
 */

import React from 'react';
import type { NodeConfigRendererProps } from '../shared/types';
import { RefSourceSelect, getFieldType } from '../shared/RefSourceSelect';
import { useAutomation2DataFlow } from '../../context/Automation2DataFlowContext';
import { isRef } from '../shared/dataRef';
import { getMimeTypeOptionsFromUploadParams } from '../runtime/fileTypeMimeMapping';
import { operatorsForType } from '../shared/conditionOperators';
import styles from '../../editor/Automation2FlowEditor.module.css';

import { useLanguage } from '../../../../providers/language/LanguageContext';

export interface StructuredCondition {
  type: 'condition';
  ref: { type: 'ref'; nodeId: string; path: (string | number)[] } | null;
  operator: string;
  value?: string | number;
}

function parseCondition(v: unknown): StructuredCondition | null {
  if (v && typeof v === 'object' && (v as StructuredCondition).type === 'condition') {
    const c = v as StructuredCondition;
    if (c.ref === null || isRef(c.ref)) return c;
  }
  return null;
}

export const IfElseNodeConfig: React.FC<NodeConfigRendererProps> = ({ params, updateParam }) => {
  const { t } = useLanguage();
  const dataFlow = useAutomation2DataFlow();

  const cond = parseCondition(params.condition);
  const ref = cond?.ref ?? null;
  const operator = cond?.operator ?? 'eq';
  const value = cond?.value ?? '';

  const fieldType = dataFlow ? getFieldType(ref, dataFlow.nodes, dataFlow.nodeOutputsPreview) : 'unknown';
  const operators = operatorsForType(fieldType);
  const currentOp = operators.find((o) => o.value === operator) ?? operators[0];
  const needsValue = currentOp?.needsValue ?? true;

  const isMimeTypeRef =
    ref && ref.path?.length >= 2 && ref.path[ref.path.length - 1] === 'mimeType';
  const sourceNode = ref && dataFlow
    ? dataFlow.nodes.find((n: { id: string; type?: string; parameters?: Record<string, unknown> }) => n.id === ref.nodeId)
    : null;
  const mimeTypeOptions =
    isMimeTypeRef && sourceNode?.type === 'input.upload' && sourceNode.parameters
      ? getMimeTypeOptionsFromUploadParams(sourceNode.parameters as Record<string, unknown>)
      : [];

  const setCondition = (next: StructuredCondition) => {
    updateParam('condition', next);
  };

  const handleRefChange = (newRef: { type: 'ref'; nodeId: string; path: (string | number)[] } | null) => {
    if (!newRef) {
      setCondition({
        type: 'condition',
        ref: null,
        operator: 'eq',
        value: '',
      });
      return;
    }
    const newType = dataFlow ? getFieldType(newRef, dataFlow.nodes, dataFlow.nodeOutputsPreview) : 'unknown';
    const newOps = operatorsForType(newType);
    setCondition({
      type: 'condition',
      ref: newRef,
      operator: newOps[0]?.value ?? 'eq',
      value: cond?.value ?? '',
    });
  };

  const handleOperatorChange = (op: string) => {
    const opDef = operators.find((o) => o.value === op);
    setCondition({
      type: 'condition',
      ref: cond?.ref ?? null,
      operator: op,
      value: opDef?.needsValue ? value : undefined,
    });
  };

  const handleValueChange = (v: string | number) => {
    setCondition({
      type: 'condition',
      ref: cond?.ref ?? null,
      operator,
      value: fieldType === 'number' ? (parseFloat(String(v)) || 0) : String(v),
    });
  };

  return (
    <div className={styles.ifElseConditionEditor}>
      <div className={styles.ifElseConditionRow}>
        <label>{t('Datenquelle')}</label>
        <RefSourceSelect value={ref} onChange={handleRefChange} placeholder={t('Formularfeld wählen')} />
      </div>
      <div className={styles.ifElseConditionRow}>
        <label>Vergleich</label>
        <select value={operator} onChange={(e) => handleOperatorChange(e.target.value)}>
          {operators.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
      </div>
      {needsValue && (
        <div className={styles.ifElseConditionRow}>
          <label>{t('Wert')}</label>
          {mimeTypeOptions.length > 0 ? (
            <select
              value={String(value ?? '')}
              onChange={(e) => handleValueChange(e.target.value)}
            >
              <option value="">{t('MIME-Typ wählen')}</option>
              {mimeTypeOptions.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label} ({o.value})
                </option>
              ))}
            </select>
          ) : (
            <input
              type={fieldType === 'number' ? 'number' : fieldType === 'date' ? 'date' : 'text'}
              value={String(value ?? '')}
              onChange={(e) =>
                handleValueChange(
                  fieldType === 'number' ? parseFloat(e.target.value) || 0 : e.target.value
                )
              }
              placeholder={
                fieldType === 'number'
                  ? '0'
                  : fieldType === 'date'
                    ? 'TT.MM.JJJJ'
                    : isMimeTypeRef
                      ? t('z.B. application/pdf')
                      : t('z.B. ch')
              }
            />
          )}
        </div>
      )}
    </div>
  );
};
