import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, test, vi } from "vitest";
import { TimeRangeFilter, datetimeTextToMs, normalizeRange, timeRangeLabel } from "@/shared/ui/TimeRangeFilter.jsx";

describe("TimeRangeFilter helpers", () => {
    test("parses strict local date time text", () => {
        const ms = datetimeTextToMs("2026-05-13 12:30");
        const date = new Date(ms);

        expect(date.getFullYear()).toBe(2026);
        expect(date.getMonth()).toBe(4);
        expect(date.getDate()).toBe(13);
        expect(date.getHours()).toBe(12);
        expect(date.getMinutes()).toBe(30);
        expect(datetimeTextToMs("2026-13-13 12:30")).toBeNull();
        expect(datetimeTextToMs("")).toBe("");
    });

    test("keeps range as a single display label", () => {
        const startMs = datetimeTextToMs("2026-05-13 10:00");
        const endMs = datetimeTextToMs("2026-05-13 12:00");

        expect(normalizeRange({ endMs, startMs })).toEqual({ endMs, startMs });
        expect(timeRangeLabel("时间", { endMs, startMs })).toContain(" - ");
        expect(timeRangeLabel("时间", {})).toBe("时间");
    });

    test("confirms picker changes without submitting an outer form", async () => {
        const user = userEvent.setup();
        const onChange = vi.fn();
        const onSubmit = vi.fn((event) => event.preventDefault());
        const startMs = datetimeTextToMs("2026-05-13 10:00");
        const endMs = datetimeTextToMs("2026-05-13 12:00");

        render(
            <form onSubmit={onSubmit}>
                <TimeRangeFilter label="活动时间" value={{ endMs, startMs }} onChange={onChange} />
            </form>,
        );

        await user.click(screen.getByRole("button", { name: /活动时间/ }));
        await user.click(screen.getByRole("button", { name: "确定" }));

        expect(onChange).toHaveBeenCalledWith({ endMs, startMs });
        expect(onSubmit).not.toHaveBeenCalled();
    });
});
