import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { KEYS } from "../../data/mock/keys";
import { I18nProvider } from "../../i18n/I18nContext";
import type { ManualImportItem, ManualImportResult } from "../../domain/types";
import { ManualImportPanel } from "./ManualImportPanel";

const backend = vi.hoisted(() => ({
  importOpportunities: vi.fn<(items: ManualImportItem[]) => Promise<{ results: ManualImportResult[] }>>(),
}));

vi.mock("../../data/DataContext", () => ({
  useRepos: () => ({
    radar: {
      importOpportunities: backend.importOpportunities,
    },
  }),
}));

function renderPanel(onImported = vi.fn()) {
  return render(
    <I18nProvider>
      <ManualImportPanel onImported={onImported} />
    </I18nProvider>,
  );
}

describe("ManualImportPanel", () => {
  beforeEach(() => {
    backend.importOpportunities.mockReset();
    localStorage.setItem(
      KEYS.uiPrefs,
      JSON.stringify({ locale: "zh-TW", currency: "TWD", theme: "system" }),
    );
  });

  it("submits the filled row and shows the returned status", async () => {
    backend.importOpportunities.mockResolvedValue({
      results: [
        { url: "https://www.threads.net/@a/post/1", opportunity_id: "o1", status: "qualified", intent_band: "high", intent_score: 88 },
      ],
    });
    const onImported = vi.fn();
    renderPanel(onImported);

    fireEvent.change(screen.getByLabelText("貼文網址"), {
      target: { value: "https://www.threads.net/@a/post/1" },
    });
    fireEvent.change(screen.getByLabelText("貼文內文"), {
      target: { value: "台北找水電師傅，急！" },
    });
    fireEvent.click(screen.getByRole("button", { name: "送出匯入" }));

    await waitFor(() => expect(backend.importOpportunities).toHaveBeenCalledTimes(1));
    expect(backend.importOpportunities).toHaveBeenCalledWith([
      { url: "https://www.threads.net/@a/post/1", text: "台北找水電師傅，急！", author: undefined },
    ]);
    expect(await screen.findByText("已收進今日商機")).toBeTruthy();
    expect(onImported).toHaveBeenCalledTimes(1);
  });

  it("blocks submit with a hint when every row is empty", async () => {
    renderPanel();
    fireEvent.click(screen.getByRole("button", { name: "送出匯入" }));
    expect(await screen.findByText("至少填一列網址與內文")).toBeTruthy();
    expect(backend.importOpportunities).not.toHaveBeenCalled();
  });

  it("parses pasted CSV into rows", async () => {
    renderPanel();
    fireEvent.click(screen.getByRole("button", { name: "改用貼上 CSV" }));
    fireEvent.change(screen.getByLabelText(/^貼上 CSV/), {
      target: {
        value: "url,text,author\nhttps://www.threads.net/@a/post/1,台北找設計師,@a",
      },
    });
    fireEvent.click(screen.getByRole("button", { name: "套用到下方列表" }));

    expect(await screen.findByDisplayValue("https://www.threads.net/@a/post/1")).toBeTruthy();
    expect(screen.getByDisplayValue("台北找設計師")).toBeTruthy();
    expect(screen.getByDisplayValue("@a")).toBeTruthy();
  });
});
