import { render, screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { MemoryRouter } from "react-router-dom"
import { API } from "@/api/API"
import { MEMORY_ROUTER_TEST_FUTURE } from "@/testing/reactRouterTest"
import type { User } from "@/lib/mock-data"
import { TerminationDetails } from "../pages/TerminationDetails"

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

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

jest.mock("@/api/API", () => ({
    API: {
        getTerminationById: jest.fn(),
        getAuditLogs: jest.fn().mockResolvedValue({
            data: { success: true, data: [] },
        }),
        updateTerminationStatus: jest.fn(),
        issueSCN: jest.fn(),
        uploadSCNResponse: jest.fn(),
        uploadTerminationDocument: jest.fn(),
        finalizeTermination: jest.fn(),
    },
}))

function reviewer(): User {
    return {
        id: "u1",
        name: "RBM User",
        email: "rbm@test.com",
        password: "",
        role: "RBM",
    }
}

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

    beforeEach(() => {
        jest.clearAllMocks()
    })

    function setup(
        terminationId = "term-missing",
        user: User | null = reviewer(),
    ) {
        render(
            <MemoryRouter future={MEMORY_ROUTER_TEST_FUTURE}>
                <TerminationDetails
                    terminationId={terminationId}
                    onBack={onBack}
                    currentUser={user}
                />
            </MemoryRouter>,
        )
    }

    it("shows fallback header when API returns no termination", async () => {
        jest.mocked(API.getTerminationById).mockResolvedValue({
            data: null,
        } as never)

        setup("term-ref-abc")

        expect(
            await screen.findByRole("heading", {
                level: 1,
                name: "term-ref-abc",
            }),
        ).toBeInTheDocument()

        await waitFor(() => {
            expect(API.getTerminationById).toHaveBeenCalledWith("term-ref-abc")
        })
    })

    it("navigates back via Back button", async () => {
        jest.mocked(API.getTerminationById).mockResolvedValue({
            data: null,
        } as never)

        const user = userEvent.setup()
        setup("term-back-test")

        await screen.findByRole("heading", { level: 1, name: "term-back-test" })

        const backButton = screen
            .getAllByRole("button")
            .find((b) => b.querySelector("svg.lucide-arrow-left"))
        expect(backButton).toBeTruthy()
        await user.click(backButton!)
        expect(onBack).toHaveBeenCalled()
    })
})
