import { screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi, beforeEach } from "vitest";
import CampaignAttributionReport from "./CampaignAttributionReport";
import { renderWithQueryClient as render } from "./test-utils";
import { ReportsAPI } from "@/apis/ReportsAPI";

vi.mock("@/apis/ReportsAPI", () => ({
  ReportsAPI: { getCampaignAttribution: vi.fn() },
}));

const dateRange = { startDate: "2026-08-01", endDate: "2026-08-31" };

describe("CampaignAttributionReport", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("muestra el loader mientras carga", () => {
    ReportsAPI.getCampaignAttribution.mockReturnValue(new Promise(() => {}));
    render(<CampaignAttributionReport companyId={1} dateRange={dateRange} onDataReady={vi.fn()} />);
    expect(document.querySelector(".animate-spin")).toBeTruthy();
  });

  it("muestra mensaje vacío cuando no hay atribuciones", async () => {
    ReportsAPI.getCampaignAttribution.mockResolvedValue([]);
    render(<CampaignAttributionReport companyId={1} dateRange={dateRange} onDataReady={vi.fn()} />);
    expect(await screen.findByText(/No hay ventas atribuidas en este período/i)).toBeInTheDocument();
  });

  it("renderiza filas de atribución y notifica los datos exportables", async () => {
    const onDataReady = vi.fn();
    ReportsAPI.getCampaignAttribution.mockResolvedValue([
      {
        idcampaign: 1,
        campaign_name: "Cumpleaños Agosto",
        idcustomer: 10,
        customer_name: "Ana Pérez",
        seller_name: "Vendedora Uno",
        sale_date: "2026-08-15",
        sale_amount: 25000,
        days_since_contact: 5,
        within_window: true,
      },
      {
        idcampaign: 1,
        campaign_name: "Cumpleaños Agosto",
        idcustomer: 11,
        customer_name: "Beto Soto",
        seller_name: null,
        sale_date: null,
        sale_amount: 0,
        days_since_contact: 40,
        within_window: false,
      },
    ]);

    render(<CampaignAttributionReport companyId={1} dateRange={dateRange} onDataReady={onDataReady} />);

    expect(await screen.findByText("Ana Pérez")).toBeInTheDocument();
    expect(screen.getByText("Beto Soto")).toBeInTheDocument();
    expect(screen.getAllByText("$25,000").length).toBeGreaterThan(0);
    expect(screen.getByText("$0")).toBeInTheDocument();
    expect(screen.getByText("1 / 2")).toBeInTheDocument();

    await waitFor(() => expect(onDataReady).toHaveBeenCalled());
    const payload = onDataReady.mock.calls[0][0];
    expect(payload.fileName).toBe("atribucion-campanas");
    expect(payload.data).toHaveLength(2);
  });

  it("no consulta la API cuando no hay companyId", () => {
    render(<CampaignAttributionReport companyId={undefined} dateRange={dateRange} onDataReady={vi.fn()} />);
    expect(ReportsAPI.getCampaignAttribution).not.toHaveBeenCalled();
  });
});
