import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ConfirmActionForm } from "@/components/forms/confirm-action-form";

afterEach(() => {
  vi.restoreAllMocks();
});

describe("ConfirmActionForm", () => {
  it("submits the server action on the first confirmed click", async () => {
    const action = vi.fn<(formData: FormData) => Promise<void>>().mockResolvedValue(undefined);
    vi.spyOn(window, "confirm").mockReturnValue(true);

    render(
      <ConfirmActionForm
        action={action}
        fields={{ id: "transfer-id" }}
        label="حذف التحويل"
        confirmMessage="هل تريد حذف التحويل؟"
      />
    );

    fireEvent.click(screen.getByRole("button", { name: "حذف التحويل" }));

    await waitFor(() => expect(action).toHaveBeenCalledTimes(1));
    const submittedData = action.mock.calls[0]?.[0] as FormData;
    expect(submittedData.get("id")).toBe("transfer-id");
  });

  it("does not submit when confirmation is cancelled", () => {
    const action = vi.fn<(formData: FormData) => Promise<void>>().mockResolvedValue(undefined);
    vi.spyOn(window, "confirm").mockReturnValue(false);

    render(
      <ConfirmActionForm
        action={action}
        fields={{ transferId: "transfer-id" }}
        label="حذف الإيصال"
        confirmMessage="هل تريد حذف الإيصال؟"
      />
    );

    fireEvent.click(screen.getByRole("button", { name: "حذف الإيصال" }));

    expect(action).not.toHaveBeenCalled();
  });
});
