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

// Mock Tiptap since it requires a full DOM with contenteditable support
vi.mock("@tiptap/react", () => {
  const EditorContent = ({ editor }: { editor: unknown }): React.JSX.Element => (
    <div data-testid="editor-content" data-editor={editor ? "ready" : "null"} />
  );

  return {
    useEditor: (): null => null,
    EditorContent,
  };
});

// Mock tiptap-markdown
vi.mock("tiptap-markdown", () => ({
  Markdown: {
    configure: vi.fn().mockReturnValue({}),
  },
}));

// Mock lowlight
vi.mock("lowlight", () => ({
  common: {},
  createLowlight: vi.fn().mockReturnValue({}),
}));

// Mock extensions
vi.mock("@tiptap/starter-kit", () => ({
  default: { configure: vi.fn().mockReturnValue({}) },
}));
vi.mock("@tiptap/extension-link", () => ({
  default: { configure: vi.fn().mockReturnValue({}) },
}));
vi.mock("@tiptap/extension-table", () => ({
  Table: { configure: vi.fn().mockReturnValue({}) },
}));
vi.mock("@tiptap/extension-table-row", () => ({
  TableRow: {},
}));
vi.mock("@tiptap/extension-table-cell", () => ({
  TableCell: {},
}));
vi.mock("@tiptap/extension-table-header", () => ({
  TableHeader: {},
}));
vi.mock("@tiptap/extension-code-block-lowlight", () => ({
  default: { configure: vi.fn().mockReturnValue({}) },
}));
vi.mock("@tiptap/extension-placeholder", () => ({
  default: { configure: vi.fn().mockReturnValue({}) },
}));

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

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

  it("should render loading state when editor is null", (): void => {
    render(<KnowledgeEditor {...defaultProps} />);
    expect(screen.getByText("Loading editor...")).toBeInTheDocument();
  });

  it("should render with knowledge-editor class", (): void => {
    // When editor is null, the loading fallback renders instead
    const { container } = render(<KnowledgeEditor {...defaultProps} />);
    expect(container.firstChild).toBeInTheDocument();
  });

  it("should accept optional placeholder prop", (): void => {
    // Smoke test that it doesn't crash with custom placeholder
    render(<KnowledgeEditor {...defaultProps} placeholder="Custom placeholder" />);
    expect(screen.getByText("Loading editor...")).toBeInTheDocument();
  });

  it("should accept optional editable prop", (): void => {
    // Smoke test that it doesn't crash when read-only
    render(<KnowledgeEditor {...defaultProps} editable={false} />);
    expect(screen.getByText("Loading editor...")).toBeInTheDocument();
  });
});
