import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { onboardingService } from "@/services/onboarding.service"
import { FinancePaymentDetailsPage } from "../pages/FinancePaymentDetailsPage"

jest.mock("sonner", () => ({
    toast: {
        error: jest.fn(),
        success: jest.fn(),
    },
}))

jest.mock("@/components/ui/DocumentPreviewModal", () => ({
    DocumentPreviewModal: () => null,
}))

jest.mock("@/services/onboarding.service", () => ({
    onboardingService: {
        getApplicationById: jest.fn(),
        getSecurityDeposit: jest.fn(),
        getSystemConfigs: jest.fn(),
        updateSecurityDeposit: jest.fn(),
    },
}))

describe("FinancePaymentDetailsPage", () => {
    const onBack = jest.fn()

    beforeEach(() => {
        jest.clearAllMocks()
        jest.mocked(onboardingService.getApplicationById).mockResolvedValue({
            id: "app-internal",
            applicationId: "APP-001",
            applicantName: "Sample Applicant",
            city: "Chennai",
            state: "TN",
            email: "a@example.com",
            phone: "9999999999",
        } as Awaited<ReturnType<typeof onboardingService.getApplicationById>>)
        jest.mocked(onboardingService.getSecurityDeposit).mockResolvedValue([])
        jest.mocked(onboardingService.getSystemConfigs).mockResolvedValue({
            SECURITY_DEPOSIT: { amount: 500000 },
            FIRST_FILL: { amount: 1500000 },
        } as never)
    })

    function setup(applicationId = "app-internal") {
        render(
            <FinancePaymentDetailsPage
                applicationId={applicationId}
                onBack={onBack}
            />,
        )
    }

    it("renders payment verification header and applicant info", async () => {
        setup()

        expect(
            await screen.findByRole("heading", {
                name: /payment verification/i,
            }),
        ).toBeInTheDocument()

        expect(screen.getByText("APP-001")).toBeInTheDocument()
        expect(screen.getByText("Sample Applicant")).toBeInTheDocument()
        expect(onboardingService.getApplicationById).toHaveBeenCalledWith(
            "app-internal",
        )
    })

    it("calls onBack when back button is used", async () => {
        const user = userEvent.setup()
        setup()

        await screen.findByRole("heading", { name: /payment verification/i })

        const backBtn = screen.getAllByRole("button").find((b) =>
            b.querySelector("svg.lucide-arrow-left"),
        )
        expect(backBtn).toBeTruthy()
        await user.click(backBtn as HTMLElement)

        expect(onBack).toHaveBeenCalled()
    })
})
