import { composeStories } from "@storybook/react"
import { screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import React from "react"
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"
import { render } from "../../../tests/render"
import * as stories from "./DatePicker.stories"

const { Default, DisabledButton } = composeStories(stories)

describe("<DatePicker />", () => {
  beforeEach(() => {
    vi.useFakeTimers({ shouldAdvanceTime: true })
    vi.setSystemTime(new Date("2025-02-17T12:33:00.000Z"))
  })

  afterEach(() => {
    vi.runOnlyPendingTimers()
    vi.useRealTimers()
  })

  test("Default", async () => {
    render(<Default />)

    await userEvent.click(screen.getByRole("button", { name: "Select a date" }))
    expect(screen.getByRole("dialog")).toBeVisible()
    expect(screen.getByText("February 2025")).toBeVisible()
    expect(screen.getByText("17")).toHaveClass("bg-bg-additional-1")
    await userEvent.click(screen.getByText("19"))
    expect(screen.getByText("19")).toHaveAttribute("aria-selected", "true")
  })

  test("keyboard navigation", async () => {
    render(<Default />)

    await userEvent.click(screen.getByRole("button", { name: "Select a date" }))
    await userEvent.keyboard("{arrowright}")
    await userEvent.click(screen.getByText("19"))
    expect(screen.getByText("19")).toHaveAttribute("aria-selected", "true")
    await userEvent.keyboard("{arrowright}")
    await userEvent.keyboard("{enter}")
    expect(screen.getByText("20")).toHaveAttribute("aria-selected", "true")
  })

  test("onSelect", async () => {
    const onSelect = vi.fn()
    render(<Default onSelect={onSelect} />)

    await userEvent.click(screen.getByRole("button", { name: "Select a date" }))
    await userEvent.click(screen.getByText("19"))

    expect(onSelect).toHaveBeenCalledWith(new Date("2025-02-19"))
  })

  test("Disabled button", () => {
    render(<DisabledButton />)

    expect(screen.getByRole("button", { name: "Select a date" })).toBeDisabled()
  })
})
