import { Button } from "../../elements/Button";
import { Component, createRef } from "preact";
import { DefaultPageProps } from "../../../types/DefaultPageProps";
import { ErrorMessage } from "../../elements/ErrorMessage";
import { Form } from "../../elements/forms/Form";
import { Margin } from "../../elements/Margin";
import { PageTitle } from "../../elements/PageTitle";
import { policyViewURL } from "../pageLinks";
import { route } from "preact-router";
import i18next from "i18next";
import { TextInput } from "../../elements/forms/TextInput";
import { InputWithTitle } from "../../elements/InputWithTitle";

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

  async onFormSubmit(formData: FormData) {
    const name = formData.get("name") as string;

    let policies: string[] = [];

    try {
      policies = await this.props.api.getPolicies();
    } catch (e: unknown) {
      const error = e as Error;
      this.errorMessageRef.current.setErrorMessage(error.message);
      return;
    }

    if (policies.includes(name)) {
      this.errorMessageRef.current.setErrorMessage(i18next.t("policy_new_already_exists"));
      return;
    }

    try {
      await this.props.api.createOrUpdatePolicy(name, " ");
      route(policyViewURL(name));
    } catch (e: unknown) {
      const error = e as Error;
      this.errorMessageRef.current.setErrorMessage(error.message);
    }
  }

  render() {
    return (
      <>
        <PageTitle title={i18next.t("policy_new_title")} />
        <div>
          <Form onSubmit={async (formData) => await this.onFormSubmit(formData)}>
            <Margin>
              <InputWithTitle title={i18next.t("common_name")}>
                <TextInput name="name" required />
              </InputWithTitle>
            </Margin>

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

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