import { screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { AllApplicationsPage } from "../pages/AllApplicationsPage"
import { renderWithProviders } from "./test-utils"
import { SHARED_APP_STATUSES } from "@/testing/constants"
import { mockOnboardingService, createGlobalMockApplication } from "@/testing/mocks"

describe("AllApplicationsPage - Robust Admin Verification", () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  const renderPage = (apps: any[] = []) => {
    ;(mockOnboardingService.getApplications as jest.Mock).mockResolvedValue({
      success: true,
      data: apps
    })
    return renderWithProviders(<AllApplicationsPage onViewDetails={jest.fn()} />, {
      preloadedState: {
        auth: { 
            user: { id: "admin-1", role: "DD Admin" } as any, 
            token: "tok", 
            isAuthenticated: true, 
            loading: false, 
            error: null 
        }
      }
    })
  }

  it("should display all application stages in a consolidated table view", async () => {
    const mockApps = [
      createGlobalMockApplication({ 
        id: "app-alpha", 
        applicantName: "Dealer Alpha", 
        overallStatus: SHARED_APP_STATUSES.LOI 
      }),
      createGlobalMockApplication({ 
        id: "app-gamma", 
        applicantName: "Dealer Gamma", 
        overallStatus: SHARED_APP_STATUSES.ARCH 
      })
    ]
    renderPage(mockApps)

    expect(await screen.findByText("Dealer Alpha")).toBeInTheDocument()
    expect(screen.getByText("Dealer Gamma")).toBeInTheDocument()
    
    // Verify status rendering in table
    expect(screen.getByText(SHARED_APP_STATUSES.LOI)).toBeInTheDocument()
    expect(screen.getByText(SHARED_APP_STATUSES.ARCH)).toBeInTheDocument()
  })

  it("should support real-time filtering via the global search input", async () => {
    const mockApps = [
      createGlobalMockApplication({ id: "app-1", applicantName: "Target Dealer", overallStatus: SHARED_APP_STATUSES.LOI }),
      createGlobalMockApplication({ id: "app-2", applicantName: "Other Business", overallStatus: SHARED_APP_STATUSES.ARCH })
    ]
    const user = userEvent.setup()
    renderPage(mockApps)

    // Search for Target (Testing frontend search logic)
    const searchInput = await screen.findByPlaceholderText(/Search/i)
    await user.type(searchInput, "Target")

    expect(screen.getByText("Target Dealer")).toBeInTheDocument()
    expect(screen.queryByText("Other Business")).not.toBeInTheDocument()
  })
})
