/**
 * Slash item `/new database` — wizard de création de table Baserow depuis l'UI
 * AcadeDoc. Utilise le bridge admin (Phase B) puis insère la nouvelle table
 * comme un node Tiptap database-view.
 */

import { useState } from "react";
import type { Editor } from "@tiptap/core";
import { Range } from "@tiptap/core";
import { IconTablePlus } from "@tabler/icons-react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MantineProvider } from "@mantine/core";
import { CreateDatabaseModal } from "./create-database-modal";

interface CreateDatabaseSlashCommandProps {
  editor: Editor;
  onDone: () => void;
  bridgeUrl?: string | null;
  workspaceId?: number;
}

function CreateDatabaseSlashWrapper({
  editor,
  onDone,
  bridgeUrl,
  workspaceId,
}: CreateDatabaseSlashCommandProps) {
  const [opened, setOpened] = useState(true);

  return (
    <CreateDatabaseModal
      opened={opened}
      onClose={() => {
        setOpened(false);
        onDone();
      }}
      editor={editor}
      bridgeUrl={bridgeUrl}
      workspaceId={workspaceId}
    />
  );
}

export function buildCreateDatabaseSlashItem(opts?: {
  bridgeUrl?: string | null;
  workspaceId?: number;
}) {
  return {
    title: "New database",
    description: "Create a new Baserow table with custom columns and formulas.",
    searchTerms: [
      "new",
      "database",
      "create",
      "table",
      "baserow",
      "nouvelle",
      "creer",
      "formule",
      "heures",
    ],
    icon: IconTablePlus,
    command: ({ editor, range }: { editor: Editor; range: Range }) => {
      editor.chain().focus().deleteRange(range).run();

      const container = document.createElement("div");
      document.body.appendChild(container);
      const teardown = () => {
        setTimeout(() => {
          if (document.body.contains(container)) {
            document.body.removeChild(container);
          }
        }, 300);
      };

      import("react-dom/client").then(({ createRoot }) => {
        const qc = new QueryClient({
          defaultOptions: { queries: { retry: false } },
        });
        const root = createRoot(container);
        root.render(
          <QueryClientProvider client={qc}>
            <MantineProvider>
              <CreateDatabaseSlashWrapper
                editor={editor}
                bridgeUrl={opts?.bridgeUrl ?? null}
                workspaceId={opts?.workspaceId}
                onDone={() => {
                  root.unmount();
                  teardown();
                }}
              />
            </MantineProvider>
          </QueryClientProvider>,
        );
      });
    },
  };
}
