/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const FILE = `${T3_HOME}/workflows/drop-test.ts`;
const DEFINITION =
  '// Original notes\r\nexport default T3.workflow("notes", { version: 1, payload: Schema.Struct({}) },\n' +
  '  Effect.fn(function* () { return "Done"; }));\r\n';

test(
  "Cancelling a sidebar file drop keeps the destination composer empty",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("Drop proof");
    const destination = await t3.thread({ project, title: "Drop destination", messages: ["hello"] });
    let previous: boolean | undefined;
    const setWorkflows = (enabled: boolean) =>
      runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          previous ??= (yield* client["server.getSettings"]({})).workflowsEnabled;
          yield* client["server.updateSettings"]({ patch: { workflowsEnabled: enabled } });
        }).pipe(Effect.scoped),
      );
    await using _fixture = {
      [Symbol.asyncDispose]: () =>
        runPromise(FileSystem.FileSystem.use((fs) => fs.remove(FILE, { force: true }))),
    };
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
        yield* fs.writeFileString(FILE, DEFINITION);
      }),
    );
    try {
      await setWorkflows(true);
      await t3.open("/workflows?definitions=true&file=drop-test.ts");
      const save = screen.getByRole("button", "Save", { exact: true });
      await save.waitFor();
      const editor = browser.locator('[contenteditable="true"]');
      await editor.waitFor();
      await browser.evaluate(() => {
        for (const host of document.querySelectorAll("*")) {
          const input = host.shadowRoot?.querySelector<HTMLElement>('[contenteditable="true"]');
          if (!input) continue;
          input.focus();
          const range = document.createRange();
          range.selectNodeContents(input.querySelector("[data-line]") ?? input);
          range.collapse(true);
          const selection = document.getSelection();
          selection?.removeAllRanges();
          selection?.addRange(range);
          break;
        }
        return null;
      });
      await browser.keyboard.type("~");
      await screen.getByText("Unsaved changes", { exact: true }).waitFor();
      if (!(await editor.textContent())?.includes("~")) throw new Error("The edit was not typed.");
      await browser.evaluate((threadId) => {
        const row = [...document.querySelectorAll<HTMLElement>("[data-thread-item]")].find(row => row.dataset.threadItem?.includes(threadId));
        if (!row) throw new Error("Destination row missing");
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(new File(["Synthetic cancelled attachment\n"], "cancelled-notes.txt", { type: "text/plain" }));
        row.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer }));
        row.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer }));
        return null;
      }, destination.threadId);
      await screen.getByText("Leave without saving?", { exact: true }).waitFor();
      await browser.evaluate(async () => {
        await Promise.all(document.getAnimations().filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
        return null;
      });
      await app.screenshot("cancel-drop-prompt");
      await screen.getByRole("button", "Cancel", { exact: true }).tap();
      await screen.getByText("Unsaved changes", { exact: true }).waitFor();
      await browser.evaluate(() => {
        for (const host of document.querySelectorAll("*")) {
          const input = host.shadowRoot?.querySelector<HTMLElement>('[contenteditable="true"]');
          if (input) {
            input.focus();
            break;
          }
        }
        return null;
      });
      await browser.keyboard.press("ControlOrMeta+z");
      await editor.filter({ hasNotText: "~" }).waitFor({ timeout: 5000 });

      await browser.locator('button:disabled').filter({ hasText: "Save" }).waitFor();
      await screen.getByRole("button", "Show sidebar", { exact: true }).tap();
      await browser.evaluate((threadId) => {
        const row = [...document.querySelectorAll<HTMLElement>("[data-sidebar-row]")].find(row => row.dataset.sidebarRow?.includes(threadId));
        if (!row) throw new Error("Destination navigation row missing");
        row.click();
        return null;
      }, destination.threadId);
      await browser.locator('[data-chat-composer-form="true"]').waitFor();
      await screen.getByRole("button", "Fork from this response").waitFor();
      await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
      await app.screenshot("destination-after-cancelled-drop");
      await expect(browser.locator('[data-chat-composer-form="true"]')).not.toContainText("cancelled-notes.txt");
    } finally {
      if (previous !== undefined) await setWorkflows(previous);
    }
  },
);
