import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it } from "vitest";

import {
  Toast,
  ToastAction,
  ToastClose,
  ToastDescription,
  ToastProvider,
  ToastTitle,
  ToastViewport
} from "./toast";

function StatefulToast() {
  const [open, setOpen] = useState(true);

  return (
    <ToastProvider>
      <Toast open={open} onOpenChange={setOpen}>
        <ToastTitle>Saved</ToastTitle>
        <ToastDescription>Launch details were updated.</ToastDescription>
        <ToastAction altText="Undo changes">Undo</ToastAction>
        <ToastClose />
      </Toast>
      <ToastViewport />
    </ToastProvider>
  );
}

describe("Toast", () => {
  it("renders viewport, title, description, action, and variant hooks", () => {
    render(
      <ToastProvider>
        <Toast open variant="destructive">
          <ToastTitle>Delete failed</ToastTitle>
          <ToastDescription>Try again in a moment.</ToastDescription>
          <ToastAction altText="Retry delete">Retry</ToastAction>
          <ToastClose />
        </Toast>
        <ToastViewport />
      </ToastProvider>
    );

    expect(screen.getByText("Delete failed").closest('[data-slot="label"]')).toBeInTheDocument();
    expect(screen.getByText("Try again in a moment.").closest('[data-slot="description"]')).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Retry" })).toHaveAttribute("data-slot", "action");
    expect(document.querySelector('[data-slot="root"]')).toHaveAttribute("data-variant", "destructive");
    expect(document.querySelector('[data-slot="viewport"]')).toBeInTheDocument();
  });

  it("closes through the close control", async () => {
    const user = userEvent.setup();

    render(<StatefulToast />);

    expect(screen.getByText("Saved")).toBeInTheDocument();

    const closeButton = document.querySelector('[data-slot="close"]');

    expect(closeButton).toBeInstanceOf(HTMLButtonElement);
    await user.click(closeButton as HTMLButtonElement);

    await waitFor(() => {
      expect(screen.queryByText("Saved")).not.toBeInTheDocument();
    });
  });
});
