import React from "react";
import { render } from "@testing-library/react";
import SuppliersOverviewClient from "@/app/(private)/dashboard/suppliers/overview/SuppliersOverviewClient";
import { DataTable } from "@/components/ui/data-table";
import { vi, describe, it, expect, beforeEach } from "vitest";

// Mock next/navigation
vi.mock("next/navigation", () => ({
  useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
  usePathname: () => "/dashboard/suppliers/overview",
  useSearchParams: () => new URLSearchParams(),
}));

// Mock PaginationWithLinks to avoid React is not defined error
vi.mock("@/components/ui/pagination-with-links", () => ({
  default: () => <div data-testid="pagination" />,
}));

// Mock DataTable to capture props
vi.mock("@/components/ui/data-table", () => ({
  DataTable: vi.fn(() => <div data-testid="data-table" />),
}));

// Mock EntityDetailPanel and everything it might pull in
vi.mock("@/components/dashboard/data-view/EntityDetailSheet", () => ({
  EntityDetailPanel: vi.fn(() => <div data-testid="detail-panel" />),
}));

// Mock actions and other potentially problematic imports
vi.mock("@/actions/settings", () => ({
  getSuppliers: vi.fn(),
  deleteSupplier: vi.fn(),
}));

// Mock columns to avoid importing problematic stuff through it
vi.mock("@/app/(private)/dashboard/suppliers/overview/columns", () => ({
  columns: [],
  getColumns: vi.fn(() => []),
}));

describe("SuppliersOverviewClient Referential Stability", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("should maintain stable handlers for DataTable across re-renders", () => {
    const initialData = {
      total: 1,
      documents: [{ id: 1, company_name: "Supplier 1" }]
    };

    const { rerender } = render(
      <SuppliersOverviewClient
        initialData={initialData as any}
        page={1}
        pageSize={10}
      />
    );

    // Get the first render's onRowClick handler
    const firstRenderHandler = vi.mocked(DataTable).mock.calls[0][0].onRowClick;

    // Trigger a re-render by changing a prop that doesn't affect handlers (like initialData)
    rerender(
      <SuppliersOverviewClient
        initialData={{ ...initialData, total: 2 } as any}
        page={1}
        pageSize={10}
      />
    );

    // Get the second render's onRowClick handler
    const secondRenderHandler = vi.mocked(DataTable).mock.calls[1][0].onRowClick;

    // Verify referential stability
    expect(firstRenderHandler).toBe(secondRenderHandler);
    expect(firstRenderHandler).toBeDefined();
  });
});
