import { TranslatedString } from "@gnu-taler/taler-util";
import { ComponentChildren, VNode } from "preact";

/**
 * Properties for form elements set at design type.
 */
export interface UIFormProps<ValType> {
  /**
   * Form file name.
   */
  name: string;

  /**
   * instruction to be shown in the field
   */
  placeholder?: TranslatedString;

  /**
   * long text help to be shown on demand
   */
  tooltip?: TranslatedString;

  /**
   * Short text to be shown next to the field
   */
  help?: TranslatedString;

  /**
   * should show as disabled and readonly
   */
  disabled?: boolean;

  /**
   * should not show
   */
  hidden?: boolean;

  /**
   * should start with focus
   */
  focus?: boolean;

  /**
   * show a mark as required
   */
  required?: boolean;

  /**
   * Label of the field.
   */
  label: TranslatedString;

  before?: Addon;
  after?: Addon;

  /**
   * converter to string and back
   */
  converter?: StringConverter<ValType>;

  handler?: UIFieldHandler<ValType>;
}

export type UIFieldHandler<T = any> = {
  /**
   * Name of the field that this handler is responsible for.
   */
  name: string | undefined;

  /**
   * Current value of the field.
   */
  value: T | undefined;

  onChange: (s: T | undefined) => void;

  error?: TranslatedString;

  /**
   * Root result of the form.
   */
  formRootResult?: any;

  hidden?: boolean;
};

export interface IconAddon {
  type: "icon";
  icon: VNode;
}

export interface ButtonAddon {
  type: "button";
  onClick: () => void;
  children: ComponentChildren;
}

export interface TextAddon {
  type: "text";
  text: TranslatedString;
}

export type Addon = IconAddon | ButtonAddon | TextAddon;

export interface StringConverter<T> {
  /**
   * Convert the form attribute value to a UI string.
   */
  toStringUI: (v?: T) => string;
  /**
   * Convert a UI string to a form attribute value.
   */
  fromStringUI: (v?: string) => T;
}
