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

// Mock KnowledgeEditor since Tiptap requires a full DOM
vi.mock("../KnowledgeEditor", () => ({
  KnowledgeEditor: ({
    content,
    onChange,
    placeholder,
  }: {
    content: string;
    onChange: (md: string) => void;
    placeholder?: string;
  }): React.JSX.Element => (
    <div data-testid="knowledge-editor" data-content={content} data-placeholder={placeholder}>
      <button
        data-testid="trigger-change"
        onClick={(): void => {
          onChange("updated content");
        }}
      >
        Change
      </button>
    </div>
  ),
}));

describe("EntryEditor", (): void => {
  const defaultProps = {
    content: "",
    onChange: vi.fn(),
  };

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

  it("should render KnowledgeEditor component", (): void => {
    render(<EntryEditor {...defaultProps} />);

    expect(screen.getByTestId("knowledge-editor")).toBeInTheDocument();
  });

  it("should have a content label", (): void => {
    render(<EntryEditor {...defaultProps} />);

    expect(screen.getByText("Content")).toBeInTheDocument();
  });

  it("should pass content to KnowledgeEditor", (): void => {
    const content = "# Test Content\n\nThis is a test.";
    render(<EntryEditor {...defaultProps} content={content} />);

    const editor = screen.getByTestId("knowledge-editor");
    expect(editor).toHaveAttribute("data-content", content);
  });

  it("should pass placeholder to KnowledgeEditor", (): void => {
    render(<EntryEditor {...defaultProps} />);

    const editor = screen.getByTestId("knowledge-editor");
    expect(editor).toHaveAttribute(
      "data-placeholder",
      "Write your content here... Supports markdown formatting."
    );
  });

  it("should forward onChange to KnowledgeEditor", async (): Promise<void> => {
    const { default: userEvent } = await import("@testing-library/user-event");
    const user = userEvent.setup();
    const onChangeMock = vi.fn();

    render(<EntryEditor {...defaultProps} onChange={onChangeMock} />);

    await user.click(screen.getByTestId("trigger-change"));
    expect(onChangeMock).toHaveBeenCalledWith("updated content");
  });

  it("should render with entry-editor wrapper class", (): void => {
    const { container } = render(<EntryEditor {...defaultProps} />);

    expect(container.querySelector(".entry-editor")).toBeInTheDocument();
  });
});
