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

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

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

const mockUser = {
    id: "u1",
    name: "DD Lead",
    email: "dd@test.com",
    password: "",
    role: "DD Lead" as const,
}

describe("FnFPage", () => {
    const onViewDetails = jest.fn()

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

    it("renders summary stats and main title after loading", async () => {
        render(
            <FnFPage currentUser={mockUser} onViewDetails={onViewDetails} />,
        )

        expect(
            await screen.findByRole("heading", {
                name: /full & final settlement cases/i,
            }),
        ).toBeInTheDocument()

        expect(screen.getByText("Newly created")).toBeInTheDocument()
        expect(screen.getByText(/^Total$/)).toBeInTheDocument()
        expect(API.getFnFSettlements).toHaveBeenCalled()
    })

    it("calls onViewDetails when View Details is clicked", async () => {
        const user = userEvent.setup()
        jest.mocked(API.getFnFSettlements).mockResolvedValue({
            data: {
                success: true,
                settlements: [
                    {
                        id: "fnf-case-1",
                        settlementId: "SET-100",
                        status: "Initiated",
                        resignationId: "RES-1",
                        resignation: { resignationId: "RES-1" },
                        outlet: {
                            code: "OUT-9",
                            name: "City Motors",
                            city: "Pune",
                            dealer: { fullName: "Dealer Person" },
                        },
                        totalReceivables: "0",
                        totalPayables: "0",
                        createdAt: "2025-02-01T10:00:00.000Z",
                    },
                ],
            },
        } as never)

        render(
            <FnFPage currentUser={mockUser} onViewDetails={onViewDetails} />,
        )

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

        expect(onViewDetails).toHaveBeenCalledWith("fnf-case-1")
    })
})
