import { CodeBlock } from "../../elements/CodeBlock";
import { Component } from "preact";
import { DefaultPageProps } from "../../../types/DefaultPageProps";
import { Margin } from "../../elements/Margin";
import { PageTitle } from "../../elements/PageTitle";
import { policyDeleteURL, policyEditURL } from "../pageLinks";
import { route } from "preact-router";
import i18next from "i18next";

export class PolicyView extends Component<
  DefaultPageProps,
  { policy: string; policyName: string }
> {
  async componentDidMount() {
    const policyName = this.props.matches["policyName"];
    const policy = await this.props.api.getPolicy(policyName);
    this.setState({
      policy,
      policyName,
    });
  }

  render() {
    if (!this.state.policy) return;
    return (
      <>
        <PageTitle title={i18next.t("policy_view_title", { policy: this.state.policyName })} />
        <div>
          <p>
            <button
              class="uk-button uk-button-primary"
              onClick={async () => {
                route(policyEditURL(this.state.policyName));
              }}
            >
              {i18next.t("common_edit")}
            </button>
            {this.state.policyName !== "default" && (
              <button
                class="uk-button uk-button-danger"
                onClick={async () => {
                  route(policyDeleteURL(this.state.policyName));
                }}
              >
                {i18next.t("common_delete")}
              </button>
            )}
          </p>

          <Margin>
            <CodeBlock language="hcl" code={this.state.policy} />
          </Margin>
        </div>
      </>
    );
  }
}