/**
 * TEAM: frontend_infra
 * @flow
 */

import * as React from "react";
// TODO: Fix this eslint issue on next edit. This is an autogenerated comment.
// eslint-disable-next-line flexport/no-legacy-dependencies
import {shallow, mount} from "enzyme";
import Toaster from "../Toaster";
import Toast, {type ToastProps} from "../Toast";
import useToaster from "../useToaster";
import TextLinkAction from "../../TextLinkAction";

function ToastDisplayer({intent, message, action}: ToastProps) {
  const {showToast} = useToaster();

  React.useEffect(() => {
    showToast({intent, message, action});
  }, [intent, message, showToast, action]);

  return null;
}

describe("Toaster", () => {
  it("renders with children", () => {
    const toaster = shallow(<Toaster>foobar</Toaster>);

    expect(toaster).toBeDefined();
  });

  it("able to display a toast successfully", () => {
    const toaster = mount(
      <Toaster>
        <ToastDisplayer intent="success" message="test" />
      </Toaster>
    );
    const toast = toaster.find(Toast);

    expect(toast).toBeDefined();
  });

  it("toast content works correctly", () => {
    const toastMessage = "john cena, can you see me?";
    const toaster = mount(
      <Toaster>
        <ToastDisplayer intent="success" message={toastMessage} />
      </Toaster>
    );
    const toast = toaster.find(Toast);

    expect(toast.text()).toMatch(toastMessage);
  });

  it("able to display multiple toasts", () => {
    const toastMessages = ["trix", "kix", "weetabix"];
    const toaster = mount(
      <Toaster>
        {toastMessages.map(message => (
          <ToastDisplayer key={message} intent="success" message={message} />
        ))}
      </Toaster>
    );
    const toasts = toaster.find(Toast);

    expect(toasts.length).toBe(toastMessages.length);

    toasts.forEach((toast, index) => {
      expect(toast.text()).toMatch(toastMessages[index]);
    });
  });

  it("able to attach callbacks to toasts successfully", () => {
    const mockFn = jest.fn();
    const toaster = mount(
      <Toaster>
        <ToastDisplayer
          intent="success"
          message="test"
          action={{type: "copy_to_clipboard", onClick: mockFn}}
        />
      </Toaster>
    );
    const toast = toaster.find(Toast);
    const actionButton = toast.find(TextLinkAction);

    actionButton.simulate("click");

    expect(mockFn.mock.calls.length).toEqual(1);
  });
});
