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

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

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

const mockUser = {
    id: "d1",
    name: "Dealer",
    email: "d@test.com",
    password: "",
    role: "Dealer" as const,
}

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

    beforeEach(() => {
        jest.clearAllMocks()
        jest.mocked(API.getDealerDashboard).mockResolvedValue({
            data: {
                outlets: [
                    {
                        id: "out-1",
                        name: "Main Studio",
                        code: "MS-01",
                        location: "MG Road",
                        city: "Bangalore",
                        state: "KA",
                        address: "Plot 1",
                    },
                ],
                profile: { businessName: "Test Dealer Co" },
            },
        } as never)
        jest.mocked(API.getRelocationRequests).mockResolvedValue({
            data: { requests: [] },
        } as never)
        jest.mocked(API.getStates).mockResolvedValue({
            data: {
                success: true,
                states: [{ id: "st-1", name: "Karnataka" }],
            },
        } as never)
        jest.mocked(API.getDistricts).mockResolvedValue({
            data: {
                success: true,
                districts: [
                    { id: "dist-1", name: "Bengaluru Urban", stateId: "st-1" },
                ],
            },
        } as never)
    })

    it("renders dealer relocation heading and stats after loading", async () => {
        render(
            <DealerRelocationPage
                currentUser={mockUser}
                onViewDetails={onViewDetails}
            />,
        )

        expect(
            await screen.findByRole("heading", {
                level: 1,
                name: /relocation requests/i,
            }),
        ).toBeInTheDocument()

        expect(screen.getByText("Total Requests")).toBeInTheDocument()
        expect(API.getDealerDashboard).toHaveBeenCalled()
        expect(API.getRelocationRequests).toHaveBeenCalled()
    })

    it("shows empty requests copy when list is empty", async () => {
        render(
            <DealerRelocationPage
                currentUser={mockUser}
                onViewDetails={onViewDetails}
            />,
        )

        expect(
            await screen.findByText(/no relocation requests found/i),
        ).toBeInTheDocument()
    })

    it("opens new relocation dialog", async () => {
        const user = userEvent.setup()
        render(
            <DealerRelocationPage
                currentUser={mockUser}
                onViewDetails={onViewDetails}
            />,
        )

        await screen.findByRole("heading", {
            level: 1,
            name: /relocation requests/i,
        })

        await user.click(
            screen.getByRole("button", {
                name: /new relocation request/i,
            }),
        )

        expect(
            screen.getByRole("heading", {
                name: /submit relocation request/i,
            }),
        ).toBeInTheDocument()
    })

    it("calls onViewDetails from table View", async () => {
        const user = userEvent.setup()
        jest.mocked(API.getRelocationRequests).mockResolvedValue({
            data: {
                requests: [
                    {
                        id: "uuid-rel",
                        requestId: "REL-777",
                        status: "Pending",
                        outlet: { name: "Main Studio" },
                        currentCity: "Bangalore",
                        newCity: "Mysore",
                        createdAt: "2025-05-01T08:00:00.000Z",
                        progressPercentage: 40,
                    },
                ],
            },
        } as never)

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

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

        expect(onViewDetails).toHaveBeenCalledWith("REL-777")
    })
})
