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

// Mock the components used within the client component to track renders
vi.mock("@/components/ui/data-table", () => ({
  DataTable: vi.fn(({ onRowClick }) => (
    <div data-testid="data-table" onClick={() => onRowClick && onRowClick({ id: 1 })}>
      DataTable
    </div>
  )),
}));

vi.mock("@/components/dashboard/data-view/EntityDetailSheet", () => ({
  EntityDetailPanel: vi.fn(({ onDataChange, onCancel }) => (
    <div data-testid="detail-panel">
      <button data-testid="btn-change" onClick={onDataChange}>Change</button>
      <button data-testid="btn-cancel" onClick={onCancel}>Cancel</button>
    </div>
  )),
}));

vi.mock("@/components/ui/pagination-with-links", () => ({
  default: () => <div data-testid="pagination">Pagination</div>,
}));

const mockRouter = { refresh: vi.fn() };
vi.mock("next/navigation", () => ({
  useRouter: () => mockRouter,
}));

vi.mock("@/auth", () => ({
  auth: vi.fn(),
  handlers: { GET: vi.fn(), POST: vi.fn() },
  signIn: vi.fn(),
  signOut: vi.fn(),
}));

vi.mock("next/cache", () => ({
  revalidatePath: vi.fn(),
  unstable_noStore: vi.fn(),
}));

describe("Brands Overview Performance: Referential Stability", () => {
  const initialData = {
    documents: [],
    total: 0,
  };

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("should maintain referential stability of event handlers across re-renders", () => {
    const { rerender } = render(
      <BrandsOverviewClient initialData={initialData} page={1} pageSize={10} />
    );

    // Capture initial handler references
    const initialRowClick = vi.mocked(DataTable).mock.calls[0][0].onRowClick;
    const initialDataChange = vi.mocked(EntityDetailPanel).mock.calls[0][0].onDataChange;
    const initialCancel = vi.mocked(EntityDetailPanel).mock.calls[0][0].onCancel;

    // Rerender with different props to force a re-render
    rerender(<BrandsOverviewClient initialData={initialData} page={1} pageSize={20} />);

    // Capture second handler references
    const secondRowClick = vi.mocked(DataTable).mock.calls[1][0].onRowClick;
    const secondDataChange = vi.mocked(EntityDetailPanel).mock.calls[1][0].onDataChange;
    const secondCancel = vi.mocked(EntityDetailPanel).mock.calls[1][0].onCancel;

    // Verify stability
    expect(initialRowClick).toBe(secondRowClick);
    expect(initialDataChange).toBe(secondDataChange);
    expect(initialCancel).toBe(secondCancel);
    expect(initialRowClick).toBeDefined();
    expect(initialDataChange).toBeDefined();
    expect(initialCancel).toBeDefined();
  });
});
