import { Button } from "../../../elements/Button";
import { Component, createRef } from "preact";
import { DefaultPageProps } from "../../../../types/DefaultPageProps";
import { ErrorMessage } from "../../../elements/ErrorMessage";
import { Form } from "../../../elements/Form";
import { Margin } from "../../../elements/Margin";
import { MarginInline } from "../../../elements/MarginInline";
import { SecretTitleElement } from "../SecretTitleElement";
import { route } from "preact-router";
import { transitViewSecretURL } from "../../pageLinks";
import i18next from "i18next";

export class TransitNew extends Component<DefaultPageProps> {
  errorMessageRef = createRef<ErrorMessage>();

  render() {
    const baseMount = this.props.matches["baseMount"];

    return (
      <>
        <SecretTitleElement
          type="transit"
          baseMount={baseMount}
          suffix={i18next.t("transit_new_key_suffix")}
        />
        <Form
          onSubmit={async (data) => {
            await this.onSubmit(data);
          }}
        >
          <Margin>
            <input
              class="uk-input uk-form-width-medium"
              name="name"
              placeholder={i18next.t("common_name")}
              type="text"
              required
            />
          </Margin>
          <Margin>
            <select class="uk-select uk-form-width-medium" name="type">
              {[
                "aes128-gcm96",
                "aes256-gcm96",
                "chacha20-poly1305",
                "ed25519",
                "ecdsa-p256",
                "ecdsa-p384",
                "ecdsa-p521",
                "rsa-2048",
                "rsa-3072",
                "rsa-4096",
              ].map((type) => (
                <option label={type} value={type}>
                  {type}
                </option>
              ))}
            </select>
          </Margin>

          <Margin>
            <ErrorMessage ref={this.errorMessageRef} />
          </Margin>

          <MarginInline>
            <Button text={i18next.t("common_create")} color="primary" type="submit" />
          </MarginInline>
        </Form>
      </>
    );
  }

  async onSubmit(data: FormData): Promise<void> {
    const baseMount = this.props.matches["baseMount"];

    const name = data.get("name") as string;
    const type = data.get("type") as string;

    try {
      await this.props.api.newTransitKey(baseMount, {
        name: name,
        type: type,
      });
      route(transitViewSecretURL(baseMount, name));
    } catch (e) {
      const error = e as Error;
      this.errorMessageRef.current.setErrorMessage(error.message);
    }
  }
}