import { screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { ApplicationDetails } from "../pages/ApplicationDetails"
import { renderWithProvidersAndRoute } from "./test-utils"
import { onboardingService } from "@/services/onboarding.service"
import { eorService } from "@/services/eor.service"
import { SHARED_APP_STATUSES } from "@/testing/constants"
import { mockOnboardingService, createGlobalMockApplication } from "@/testing/mocks"

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

  const renderAdminDetails = (overrides = {}) => {
    const appData = createGlobalMockApplication(overrides)
    ;(mockOnboardingService.getApplicationById as jest.Mock).mockResolvedValue(appData)
    return renderWithProvidersAndRoute(<ApplicationDetails />, {
      initialEntry: `/applications/${appData.id}`,
      routePath: "/applications/:id",
      preloadedState: {
        auth: { 
          user: { id: "admin-1", name: "Admin", role: "DD Admin" } as any, 
          token: "test-token", 
          isAuthenticated: true, 
          loading: false, 
          error: null 
        }
      }
    })
  }

  it("should verify the Admin review and approval loop during FDD stage", async () => {
    const user = userEvent.setup()
    
    // 1. Mock FDD status with a realistic report finding
    renderAdminDetails({ 
      overallStatus: SHARED_APP_STATUSES.FDD,
      reports: [{
        id: "rep-1",
        findings: "Audit verified: Positive cash flows and assets.",
        recommendation: "Green"
      }]
    })

    // 2. Tab switching logic (audit content is mocked; approval actions are what we assert)
    const fddTab = await screen.findByTestId("onboarding-tab-trigger-fdd")
    await user.click(fddTab)

    await screen.findByTestId("onboarding-tab-content-fdd")

    expect(screen.getByTestId("onboarding-details-approve-button")).toBeInTheDocument()
  })

  it("should enforce role-based access to administrative actions", async () => {
    const appData = createGlobalMockApplication({ overallStatus: SHARED_APP_STATUSES.LOA })
    ;(onboardingService.getApplicationById as jest.Mock).mockResolvedValue(appData)

    renderWithProvidersAndRoute(<ApplicationDetails />, {
      initialEntry: `/applications/${appData.id}`,
      routePath: "/applications/:id",
      preloadedState: {
        auth: { 
          user: { id: "audit-1", name: "Auditor", role: "FDD" } as any, 
          token: "tok", 
          isAuthenticated: true, 
          loading: false, 
          error: null 
        }
      }
    })

    // Verify 'Reject' and 'Approve' buttons ARE NOT present for FDD role during LOA stage
    await waitFor(() => {
        expect(screen.queryByTestId("onboarding-details-approve-button")).not.toBeInTheDocument()
        expect(screen.queryByTestId("onboarding-details-reject-button")).not.toBeInTheDocument()
    })
  })

  it("should verify EOR compliance check tracking", async () => {
    const user = userEvent.setup()
    ;(eorService.getChecklist as jest.Mock).mockResolvedValue({
      success: true,
      data: {
        id: "eor-1",
        items: [{
          id: "item-1",
          description: "Mandatory Training",
          isCompliant: false,
          proofDocument: { fileName: "training-proof.pdf" },
        }]
      }
    })

    renderAdminDetails({ overallStatus: SHARED_APP_STATUSES.EOR })

    await user.click(await screen.findByTestId("onboarding-tab-trigger-eor"))
    expect(await screen.findByText(/Mandatory Training/i)).toBeInTheDocument()
    
    // Verify item toggling logic
    const verifyBtn = screen.getByTestId("onboarding-eor-verify-btn-0")
    await user.click(verifyBtn)

    await waitFor(() => {
      expect(eorService.updateItem).toHaveBeenCalled()
    })
  })
})
