import React from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
  render,
  screen,
  waitFor,
  within,
  fireEvent,
} from "@testing-library/react";
import DataGrid from "../DataGrid";

vi.mock("@/app/lib/settings", () => ({
  useSettings: () => ({ baseUrl: "http://localhost:4052", apiKey: "test" }),
}));

vi.mock("@/app/lib/store", () => {
  const flags = {
    enableModules: true,
    enableWorkspaceSettings: true,
    enableAuthConfig: true,
    enableClientStatistics: true,
    enableSdkDocs: true,
    enableClusterHealth: true,
    compactDatagrid: false,
    showRowNumbers: true,
    showColumnIcons: true,
    showDocumentIcons: true,
    sortColumnsByDdl: false,
    hideNullColumns: false,
  };
  const preferences = {
    sidebarMinWidth: 10,
    sidebarMaxWidth: 30,
    inspectorMinWidth: 12,
    inspectorMaxWidth: 40,
    sidebarOpen: true,
    inspectorOpen: true,
    autoFitColumnWidth: true,
    maxAutoColumnWidth: 400,
  };
  return {
    useAppStore: () => ({
      flags,
      preferences,
    }),
  };
});

const fetchRowsMock = vi.fn();

vi.mock("@/app/lib/api", async () => {
  const actual =
    await vi.importActual<typeof import("@/app/lib/api")>("@/app/lib/api");
  return {
    ...actual,
    fetchRows: (...args: unknown[]) => fetchRowsMock(...args),
    ApiError: class ApiError extends Error {
      status: number;
      code: string;
      constructor(message: string, status = 0, code = "TEST") {
        super(message);
        this.status = status;
        this.code = code;
      }
    },
  };
});

const columnsA = [
  { column_name: "id", data_type: "text" },
  { column_name: "name", data_type: "text" },
];

const rowsA = [
  { id: "b", name: "bravo" },
  { id: "a", name: "alpha" },
];

const columnsB = [
  { column_name: "created_at", data_type: "timestamp" },
  { column_name: "title", data_type: "text" },
];

const rowsB = [
  { created_at: "2024-01-01T00:00:00Z", title: "old" },
  { created_at: "2024-02-01T00:00:00Z", title: "new" },
];

describe("DataGrid sorting resets on table change", () => {
  beforeEach(() => {
    fetchRowsMock.mockReset();
  });

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

  it("applies default created_at desc after switching tables and clears prior sort", async () => {
    fetchRowsMock.mockResolvedValueOnce(rowsA);

    const onMutation = vi.fn();
    const { rerender } = render(
      <DataGrid
        table={{ table_name: "table_a", table_schema: "public" }}
        columns={columnsA as any}
        clientName="client1"
        refreshKey={0}
        onMutation={onMutation}
      />,
    );

    // Wait for first load
    await waitFor(() => expect(fetchRowsMock).toHaveBeenCalledTimes(1));

    // Click id header to sort rows by id
    const idHeader = screen.getByText("id");
    fireEvent.click(idHeader);

    // Ensure the order is id-sorted (alpha then bravo)
    await waitFor(() => {
      const rows = screen
        .getAllByRole("row")
        .filter((r) => within(r).queryByText("alpha"));
      expect(rows.length).toBeGreaterThan(0);
    });

    // Switch to table B with created_at column
    fetchRowsMock.mockResolvedValueOnce(rowsB);
    rerender(
      <DataGrid
        table={{ table_name: "table_b", table_schema: "public" }}
        columns={columnsB as any}
        clientName="client1"
        refreshKey={0}
        onMutation={onMutation}
      />,
    );

    await waitFor(() => expect(fetchRowsMock).toHaveBeenCalledTimes(2));

    // Default sort should be by created_at desc: "new" first
    await waitFor(() => {
      const bodyRows = screen
        .getAllByRole("row")
        .filter((r) => within(r).queryByText("new"));
      expect(bodyRows.length).toBeGreaterThan(0);
      const firstRow = bodyRows[0];
      expect(within(firstRow).getByText("new")).toBeInTheDocument();
    });
  });
});
