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

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

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

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

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

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

    it("renders management heading and empty table after fetch", async () => {
        render(
            <RelocationRequestPage
                currentUser={mockUser}
                onViewDetails={onViewDetails}
            />,
        )

        expect(
            await screen.findByRole("heading", {
                name: /relocation request management/i,
            }),
        ).toBeInTheDocument()

        expect(screen.getByText("Total Requests")).toBeInTheDocument()
        expect(
            await screen.findByText(/no relocation requests found/i),
        ).toBeInTheDocument()
        expect(API.getRelocationRequests).toHaveBeenCalled()
    })

    it("calls onViewDetails when View is clicked", async () => {
        const user = userEvent.setup()
        jest.mocked(API.getRelocationRequests).mockResolvedValue({
            data: {
                success: true,
                requests: [
                    {
                        id: "rel-row-1",
                        requestId: "REL-500",
                        status: "Pending ASM Review",
                        outlet: { code: "OUT-1", name: "North Hub" },
                        currentLocation: "Old Street",
                        proposedLocation: "New Park",
                        distance: "12 km",
                        currentStage: "ASM Review",
                        progressPercentage: 25,
                        createdAt: "2025-04-01T09:00:00.000Z",
                    },
                ],
            },
        } as never)

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

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

        expect(onViewDetails).toHaveBeenCalledWith("rel-row-1")
    })
})
