import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { HostCountriesPage } from "./HostCountriesPage.jsx";
import { useHostCountriesPage } from "@/features/host-org/hooks/useHostCountriesPage.js";

const mocks = vi.hoisted(() => ({
    setCountryForm: vi.fn(),
}));

vi.mock("@/features/host-org/hooks/useHostCountriesPage.js", () => ({
    useHostCountriesPage: vi.fn(),
}));

afterEach(() => {
    vi.clearAllMocks();
});

test("country code field is editable when editing a country with update permission", () => {
    vi.mocked(useHostCountriesPage).mockReturnValue(pageFixture());

    render(<HostCountriesPage />);

    const countryCodeInput = screen.getByRole("textbox", { name: /国家码/ });
    expect(countryCodeInput).not.toBeDisabled();

    fireEvent.change(countryCodeInput, { target: { value: "PHL" } });

    expect(mocks.setCountryForm).toHaveBeenCalledWith(expect.objectContaining({ countryCode: "PHL" }));
});

test("country code field stays disabled when editing without update permission", () => {
    vi.mocked(useHostCountriesPage).mockReturnValue(
        pageFixture({
            abilities: { ...pageFixture().abilities, canUpdate: false },
        }),
    );

    render(<HostCountriesPage />);

    expect(screen.getByRole("textbox", { name: /国家码/ })).toBeDisabled();
});

function pageFixture(patch = {}) {
    return {
        abilities: {
            canCreate: true,
            canStatus: true,
            canUpdate: true,
            canView: true,
        },
        activeAction: "edit",
        changeEnabledStatus: vi.fn(),
        changeQuery: vi.fn(),
        closeAction: vi.fn(),
        countryForm: countryFormFixture(),
        data: { items: [], total: 0 },
        editingCountry: countryFixture(),
        enabledStatus: "",
        error: null,
        loading: false,
        loadingAction: "",
        openCreateCountry: vi.fn(),
        openEditCountry: vi.fn(),
        query: "",
        reload: vi.fn(),
        resetFilters: vi.fn(),
        setCountryForm: mocks.setCountryForm,
        submitCountry: vi.fn(),
        toggleCountry: vi.fn(),
        ...patch,
    };
}

function countryFormFixture() {
    return {
        countryCode: "PH",
        countryDisplayName: "菲律宾",
        countryName: "Philippines",
        enabled: true,
        flag: "🇵🇭",
        isoAlpha3: "PHL",
        isoNumeric: "608",
        phoneCountryCode: "+63",
        sortOrder: 1770,
    };
}

function countryFixture() {
    return {
        ...countryFormFixture(),
        countryId: 12,
        updatedAtMs: 1783578249000,
    };
}
