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

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

jest.mock("@/api/API", () => ({
    API: {
        getTerminations: jest.fn(),
        getDealers: jest.fn(),
        createTermination: jest.fn(),
        uploadTerminationDocument: jest.fn(),
    },
}))

const superAdmin = {
    id: "adm",
    name: "Admin",
    email: "a@test.com",
    password: "",
    role: "Super Admin" as const,
}

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

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

    it("renders restricted alert and empty list after loading", async () => {
        render(
            <TerminationPage
                currentUser={superAdmin}
                onViewDetails={onViewDetails}
            />,
        )

        expect(
            await screen.findByText(/restricted access/i),
        ).toBeInTheDocument()
        expect(screen.getByText("Total Cases")).toBeInTheDocument()
        expect(
            await screen.findByText(/no termination requests found/i),
        ).toBeInTheDocument()
        expect(API.getTerminations).toHaveBeenCalled()
    })

    it("calls onViewDetails when View Details is clicked", async () => {
        const user = userEvent.setup()
        const rowId =
            "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"

        jest.mocked(API.getTerminations).mockResolvedValue({
            data: {
                success: true,
                terminations: [
                    {
                        id: rowId,
                        requestId: "TR-9001",
                        status: "Pending RBM Review",
                        currentStage: "RBM Review",
                        severity: "Medium",
                        category: "Operational",
                        proposedLwd: "2026-06-30",
                        createdAt: "2026-03-01T10:00:00.000Z",
                        dealer: {
                            businessName: "North Wing Motors",
                            registeredAddress: "Indore, MP",
                        },
                    },
                ],
            },
        } as never)

        render(
            <TerminationPage
                currentUser={superAdmin}
                onViewDetails={onViewDetails}
            />,
        )

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

        expect(onViewDetails).toHaveBeenCalledWith(rowId)
    })
})
