import { Button } from "./Button";
import { CodeBlock } from "./CodeBlock";
import { Component, JSX, createRef } from "preact";
import { addClipboardNotifications } from "../../utils/clipboardNotifs";
import ClipboardJS from "clipboard";
import FileSaver from "file-saver";
import i18next from "i18next";
import { InlineButtonBox } from "./InlineButtonBox";

export type CopyableBoxProps = {
  title: string;
  contentString: string;
  goBack?: () => void;
};

export class CopyableBox extends Component<CopyableBoxProps> {
  copyButtonRef = createRef<HTMLButtonElement>();

  saveAsFile(): void {
    const blob = new Blob([this.props.contentString], {
      type: "text/plain;charset=utf-8",
    });
    FileSaver.saveAs(blob, "result.txt");
  }

  componentDidMount(): void {
    const clipboard = new ClipboardJS(this.copyButtonRef.current);
    addClipboardNotifications(clipboard, 600);
  }

  render(): JSX.Element {
    return (
      <div>
        <div>
          <h2>{this.props.title}</h2>
        </div>
        <CodeBlock code={this.props.contentString} />
        <InlineButtonBox>
          <Button
            text={i18next.t("copy_box_download_btn")}
            color="primary"
            onClick={() => this.saveAsFile()}
          />
          <Button
            text={i18next.t("copy_box_copy_btn")}
            color="primary"
            buttonRef={this.copyButtonRef}
            data-clipboard-text={this.props.contentString}
          />
          {this.props.goBack && (
            <Button text={i18next.t("common_back")} color="secondary" onClick={this.props.goBack} />
          )}
        </InlineButtonBox>
      </div>
    );
  }
}