import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { WidgetConfigDialog } from "../WidgetConfigDialog";

describe("WidgetConfigDialog", (): void => {
  const defaultProps = {
    widgetId: "TasksWidget-abc123",
    open: true,
    onClose: vi.fn(),
  };

  beforeEach((): void => {
    vi.clearAllMocks();
  });

  it("should render nothing when closed", (): void => {
    const { container } = render(<WidgetConfigDialog {...defaultProps} open={false} />);
    expect(container.innerHTML).toBe("");
  });

  it("should render dialog when open", (): void => {
    render(<WidgetConfigDialog {...defaultProps} />);
    expect(screen.getByRole("dialog", { name: "Widget Settings" })).toBeInTheDocument();
  });

  it("should show widget name in header", (): void => {
    render(<WidgetConfigDialog {...defaultProps} />);
    // TasksWidget is registered with displayName "Tasks"
    expect(screen.getByText(/Tasks.*Settings/)).toBeInTheDocument();
  });

  it("should show placeholder message when no config schema", (): void => {
    render(<WidgetConfigDialog {...defaultProps} />);
    expect(
      screen.getByText("No configuration options available for this widget yet.")
    ).toBeInTheDocument();
  });

  it("should call onClose when close button is clicked", async (): Promise<void> => {
    const user = userEvent.setup();
    render(<WidgetConfigDialog {...defaultProps} />);

    await user.click(screen.getByLabelText("Close"));
    expect(defaultProps.onClose).toHaveBeenCalledTimes(1);
  });

  it("should call onClose when footer Close button is clicked", async (): Promise<void> => {
    const user = userEvent.setup();
    render(<WidgetConfigDialog {...defaultProps} />);

    // Footer has a "Close" text button
    await user.click(screen.getByText("Close"));
    expect(defaultProps.onClose).toHaveBeenCalledTimes(1);
  });

  it("should handle unknown widget type gracefully", (): void => {
    render(<WidgetConfigDialog {...defaultProps} widgetId="UnknownWidget-xyz" />);
    // Should show fallback "Widget Settings" when type is not in registry
    expect(screen.getByText("Widget Settings")).toBeInTheDocument();
  });
});
