import { i18n, TranslatedString } from "@gnu-taler/taler-util";
import { Fragment, h, VNode } from "preact";
import { useState } from "preact/hooks";
import { UIFormProps } from "../FormProvider.js";
import { noHandlerPropsAndNoContextForField } from "./InputArray.js";
import { InputSelectOne } from "./InputSelectOne.js";

export interface ChoiceH<V> {
  label: TranslatedString;
  value: V;
}

export function InputDrilldown(
  props: {
    choices: any;
  } & UIFormProps<any>,
): VNode {
  const { hidden, choices, label, tooltip, help, required, converter } = props;
  const { value, onChange } =
    props.handler ?? noHandlerPropsAndNoContextForField(props.name);
  if (hidden) {
    return <Fragment />;
  }

  const [choiceStack, setChoiceStack] = useState<string[]>([]);

  let ch = props.choices;

  let inputs = [];

  for (let lvl = 0; lvl < choiceStack.length + 1; lvl++) {
    if (typeof ch === "string") {
      break;
    }
    inputs.push(
      <InputSelectOne
        name={props.name}
        label={i18n.str`${props.label} (Classification level ${lvl + 1})`}
        required={required}
        handler={{
          name: choiceStack.join(","),
          onChange(x) {
            if (x != null) {
              const cs = [...choiceStack.slice(0, lvl), x];
              let myCh = props.choices;
              for (let c of cs) {
                myCh = myCh[c];
              }
              if (typeof myCh === "string") {
                onChange(myCh);
              }
              setChoiceStack(cs);
            } else {
              setChoiceStack([...choiceStack.slice(0, lvl)]);
              onChange(undefined);
            }
          },
          value: choiceStack[lvl],
        }}
        choices={Object.keys(ch).map((x) => ({
          label: x as TranslatedString,
          value: x,
        }))}
      />,
    );

    ch = ch[choiceStack[lvl]];
  }

  return <>{inputs}</>;
}
