import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { createEmptyActivityTemplateForm } from "@/features/activity-templates/model.js";
import { ActivityTemplateEditorDrawer } from "./ActivityTemplateEditorDrawer.jsx";

vi.mock("@mui/material/Drawer", () => ({
    default: ({ children, open }) => (open ? <div>{children}</div> : null),
}));

vi.mock("@/features/activity-templates/components/ActivityPhonePreview.jsx", () => ({
    ActivityPhonePreview: () => <aside>手机预览</aside>,
}));

vi.mock("@/shared/ui/TimeRangeFilter.jsx", () => ({
    TimeRangeFilter: ({ disabled, label }) => <input aria-label={label} disabled={disabled} />,
}));

vi.mock("@/shared/ui/MultiValueAutocomplete.jsx", () => ({
    MultiValueAutocomplete: ({ disabled, label, required = false }) => (
        <input aria-label={label} disabled={disabled} required={required} />
    ),
}));

test("create permission alone keeps create fields and draft action editable", () => {
    renderEditor({
        abilities: abilities({ canCreate: true, canUpdate: false }),
        form: createEmptyActivityTemplateForm("lalu"),
        mode: "create",
    });

    expect(screen.getByRole("textbox", { name: /内部名称/ })).toBeEnabled();
    expect(screen.getByRole("button", { name: "保存草稿" })).toBeEnabled();
});

test("publish-only English content and region fields do not use native required validation", () => {
    renderEditor({ form: createEmptyActivityTemplateForm("lalu"), mode: "create" });

    expect(screen.getByRole("textbox", { name: "活动标题（英语）" })).not.toBeRequired();
    expect(screen.getByRole("textbox", { name: "指定投放区域" })).not.toBeRequired();

    fireEvent.click(screen.getByRole("button", { name: "规则文案" }));
    expect(screen.getByRole("textbox", { name: "活动规则（英语）" })).not.toBeRequired();
});

test("version snapshots never expose a disable action", () => {
    const onDisable = vi.fn();
    const form = {
        ...createEmptyActivityTemplateForm("lalu"),
        lifecycleStatus: "published",
        publishedVersion: 4,
        revision: 12,
        status: "published",
        templateCode: "gift_challenge_2026",
        templateId: "template-101",
    };

    renderEditor({ form, mode: "version", onDisable });

    expect(screen.getByText("发布版本为不可变快照。")).toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /停用/ })).not.toBeInTheDocument();
    expect(onDisable).not.toHaveBeenCalled();
});

test("only exposes reload for an optimistic revision conflict", () => {
    const form = {
        ...createEmptyActivityTemplateForm("lalu"),
        templateCode: "gift_challenge_2026",
        templateId: "template-101",
    };
    const { rerender } = renderEditor({
        form,
        mode: "edit",
        validationIssues: [{ code: "save_failed", field: "name", message: "保存失败" }],
    });

    expect(screen.queryByRole("button", { name: "重新加载" })).not.toBeInTheDocument();

    const props = editorProps({
        form,
        mode: "edit",
        validationIssues: [{ code: "revision_conflict", field: "revision", message: "版本已变化" }],
    });
    rerender(<ActivityTemplateEditorDrawer {...props} />);
    expect(screen.getByRole("button", { name: "重新加载" })).toBeEnabled();
});

function renderEditor(patch = {}) {
    return render(<ActivityTemplateEditorDrawer {...editorProps(patch)} />);
}

function editorProps(patch = {}) {
    return {
        abilities: abilities(),
        dirty: false,
        form: createEmptyActivityTemplateForm("lalu"),
        gifts: [],
        giftsLoading: false,
        loading: false,
        loadingRegions: false,
        mode: "create",
        onClose: vi.fn(),
        onDisable: vi.fn(),
        onPublish: vi.fn(),
        onReload: vi.fn(),
        onSubmit: vi.fn((event) => event.preventDefault()),
        open: true,
        regionOptions: [],
        resourceGroups: [],
        saving: false,
        setForm: vi.fn(),
        validationIssues: [],
        ...patch,
    };
}

function abilities(patch = {}) {
    return {
        canCreate: true,
        canDelete: true,
        canPublish: true,
        canUpdate: true,
        canView: true,
        ...patch,
    };
}
