import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { API } from "@/api/API"
import { FinanceFnFPage } from "../pages/FinanceFnFPage"

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

jest.mock("@/api/API", () => ({
    API: {
        getFnFSettlements: jest.fn(),
    },
}))

describe("FinanceFnFPage", () => {
    const onViewFnFDetails = jest.fn()

    beforeEach(() => {
        jest.clearAllMocks()
        jest.mocked(API.getFnFSettlements).mockResolvedValue({
            data: { success: true, settlements: [] },
        } as never)
    })

    it("renders finance header and queue after loading", async () => {
        render(<FinanceFnFPage onViewFnFDetails={onViewFnFDetails} />)

        expect(
            await screen.findByRole("heading", {
                level: 1,
                name: /f&f financial settlement/i,
            }),
        ).toBeInTheDocument()

        expect(
            screen.getByRole("heading", { name: /f&f settlement queue/i }),
        ).toBeInTheDocument()
        expect(API.getFnFSettlements).toHaveBeenCalled()
    })

    it("calls onViewFnFDetails when View Details is clicked", async () => {
        const user = userEvent.setup()
        jest.mocked(API.getFnFSettlements).mockResolvedValue({
            data: {
                success: true,
                settlements: [
                    {
                        id: "finance-fnf-99",
                        settlementId: "FNF-99",
                        status: "Calculated",
                        resignationId: "R-9",
                        resignation: { resignationId: "R-9" },
                        outlet: {
                            code: "DLR-X",
                            city: "Mumbai",
                            dealer: { fullName: "Finance Dealer" },
                        },
                        totalPayables: "10000",
                        totalReceivables: "5000",
                        netAmount: "-2500",
                        createdAt: "2025-03-01T12:00:00.000Z",
                    },
                ],
            },
        } as never)

        render(<FinanceFnFPage onViewFnFDetails={onViewFnFDetails} />)

        await user.click(
            await screen.findByRole("button", { name: /view details/i }),
        )

        expect(onViewFnFDetails).toHaveBeenCalledWith("finance-fnf-99")
    })
})
