import { screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { FDDApplicationDetails } from "../pages/FDDApplicationDetails"
import { renderWithProvidersAndRoute } from "./test-utils"
import { SHARED_APP_STATUSES } from "@/testing/constants"
import { createGlobalMockApplication } from "@/testing/mocks"
import { API } from "@/api/API"

describe("FDD Agency Flow - Robust Submission Verification", () => {
    beforeEach(() => {
        jest.clearAllMocks()
    })

    const renderAgencyView = (overrides = {}) => {
        const appData = createGlobalMockApplication({
            overallStatus: SHARED_APP_STATUSES.FDD,
            ...overrides,
        })

        return renderWithProvidersAndRoute(<FDDApplicationDetails />, {
            initialEntry: `/fdd-details/${appData.id}`,
            routePath: "/fdd-details/:id",
            preloadedState: {
                auth: {
                    user: { id: "agency-1", role: "FDD" } as any,
                    token: "agency-token",
                    isAuthenticated: true,
                    loading: false,
                    error: null,
                },
            },
        })
    }

    it("should allow an agency user to submit a formal FDD audit report", async () => {
        const user = userEvent.setup()
        renderAgencyView()

        expect(await screen.findByTestId("onboarding-fdd-details-name")).toHaveTextContent(/Global Test Applicant/i)

        // 1. Select document type (verify dropdown functionality)
        const select = await screen.findByTestId("onboarding-fdd-details-doc-type-select")
        await user.selectOptions(select, "FDD Final Audit Report")

        // 2. Upload file (verify upload trigger)
        const file = new File(["dummy audit content"], "fdd_audit.pdf", { type: "application/pdf" })
        const input = screen.getByTestId("onboarding-fdd-details-file-input")
        await user.upload(input, file)

        // 3. Verify actual API integration (Testing the real integration path)
        await waitFor(() => {
            expect(API.uploadDocument).toHaveBeenCalled()
            expect(API.submitFddReport).toHaveBeenCalledWith(
                expect.objectContaining({
                    assignmentId: "fdd-asg-test",
                    recommendation: "REVIEW_PENDING",
                })
            )
        })
    })

    it("should support flagging non-responsive applicants and track status updates", async () => {
        const user = userEvent.setup()
        renderAgencyView()

        const flagBtn = await screen.findByTestId("onboarding-fdd-details-flag-btn")
        await user.click(flagBtn)

        expect(
            await screen.findByTestId("onboarding-fdd-details-flag-modal-title")
        ).toHaveTextContent(/Flag Applicant/i)

        const confirmBtn = screen.getByTestId("onboarding-fdd-details-flag-modal-confirm")
        await user.click(confirmBtn)

        await waitFor(() => {
            expect(API.flagNonResponsive).toHaveBeenCalled()
        })
    })

    it("should handle error states during document upload", async () => {
        ;(API.uploadDocument as jest.Mock).mockRejectedValue(new Error("Upload Failed"))
        const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
        
        const user = userEvent.setup()
        renderAgencyView()

        const select = await screen.findByTestId("onboarding-fdd-details-doc-type-select")
        await user.selectOptions(select, "FDD Final Audit Report")
        const input = screen.getByTestId("onboarding-fdd-details-file-input")
        const file = new File(["error"], "fail.pdf", { type: "application/pdf" })
        await user.upload(input, file)

        // Wait for error logging or UI feedback (if implemented)
        await waitFor(() => {
            expect(API.uploadDocument).toHaveBeenCalled()
        })
        
        consoleSpy.mockRestore()
    })
})
