import { Button } from "../elements/Button";
import { Component, JSX, 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 { MarginInline } from "../elements/MarginInline";
import { route } from "preact-router";
import i18next from "i18next";
import { TextInput } from "../elements/forms/TextInput";
import { PasswordInput } from "../elements/forms/PasswordInput";
import { InputWithTitle } from "../elements/InputWithTitle";

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

  render(): JSX.Element {
    return (
      <Form onSubmit={(data) => this.onSubmit(data)}>
        <Margin>
          <InputWithTitle title={i18next.t("log_in_username_input")}>
            <TextInput name="username" required />
          </InputWithTitle>
        </Margin>

        <Margin>
          <InputWithTitle title={i18next.t("log_in_password_input")}>
            <PasswordInput name="password" required />
          </InputWithTitle>
        </Margin>

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

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

  async onSubmit(data: FormData): Promise<void> {
    const previousToken = this.props.settings.token;

    try {
      const res = await this.props.api.usernameLogin(
        data.get("username") as string,
        data.get("password") as string,
      );
      this.props.settings.token = res;
      route("/");
    } catch (e: unknown) {
      const error = e as Error;
      this.errorMessageRef.current.setErrorMessage(error.message);
      this.props.settings.token = previousToken;
    }
  }
}