/**
 * Upload node config – allowed file types (multi-select), max size, multiple files.
 * Uses shared fileTypeMimeMapping for option definitions.
 */

import React from 'react';
import type { NodeConfigRendererProps } from './types';
import { getAcceptValues, parseAllowedTypes } from '../runtime/fileTypeMimeMapping';
import styles from '../../editor/Automation2FlowEditor.module.css';

function buildAcceptString(allowedTypes: string[]): string {
  if (allowedTypes.length === 0) return '';
  return allowedTypes.join(',');
}

/** Get HTML accept string from node config (for file input). */
export function getAcceptStringFromConfig(config: Record<string, unknown>): string {
  const types = parseAllowedTypes(config);
  return buildAcceptString(types);
}

const FILE_TYPE_CHIP_OPTIONS = getAcceptValues();

export const UploadNodeConfig: React.FC<NodeConfigRendererProps> = ({ params, updateParam }) => {
  const allowedTypes = parseAllowedTypes(params);
  const maxSize = (params.maxSize as number) ?? 10;
  const multiple = (params.multiple as boolean) ?? false;

  const toggleType = (value: string) => {
    const next = allowedTypes.includes(value)
      ? allowedTypes.filter((v) => v !== value)
      : [...allowedTypes, value];
    updateParam('allowedTypes', next);
    updateParam('accept', next.length ? buildAcceptString(next) : ''); // legacy compat for backend
  };

  return (
    <div className={styles.uploadNodeConfig}>
      <div className={styles.configBlock}>
        <label>Erlaubte Dateitypen</label>
        <p className={styles.configHint}>
          Mehrfachauswahl möglich. Keine Auswahl = alle Typen erlaubt.
        </p>
        <div className={styles.fileTypeChips}>
          {FILE_TYPE_CHIP_OPTIONS.map((opt) => (
            <label key={opt.value} className={styles.fileTypeChip}>
              <input
                type="checkbox"
                checked={allowedTypes.includes(opt.value)}
                onChange={() => toggleType(opt.value)}
              />
              <span>{opt.label}</span>
            </label>
          ))}
        </div>
      </div>
      <div className={styles.configBlock}>
        <label>Max. Größe (MB)</label>
        <input
          type="number"
          min={0.1}
          max={500}
          step={1}
          value={maxSize}
          onChange={(e) => updateParam('maxSize', parseFloat(e.target.value) || 10)}
        />
      </div>
      <div className={styles.configBlock}>
        <label>
          <input
            type="checkbox"
            checked={multiple}
            onChange={(e) => updateParam('multiple', e.target.checked)}
          />
          Mehrere Dateien erlauben
        </label>
      </div>
    </div>
  );
};
