import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'

import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'

describe ('PostOriginalCreatedTimeField', () => {
  it ('updates from and before values', () => {
    const setFrom = vi.fn ()
    const setBefore = vi.fn ()

    render (
        <PostOriginalCreatedTimeField
            originalCreatedFrom={null}
            setOriginalCreatedFrom={setFrom}
            originalCreatedBefore={null}
            setOriginalCreatedBefore={setBefore}/>,
    )

    const inputs = screen.getAllByDisplayValue ('')
    fireEvent.change (inputs[0], { target: { value: '2026-01-02T03:04' } })
    fireEvent.change (inputs[1], { target: { value: '2026-01-03T03:04' } })

    expect (setFrom).toHaveBeenCalledWith (expect.any (String))
    expect (setBefore).toHaveBeenCalledWith (expect.any (String))
  })

  it ('infers an exclusive before value on blur', () => {
    const setBefore = vi.fn ()

    render (
        <PostOriginalCreatedTimeField
            originalCreatedFrom={null}
            setOriginalCreatedFrom={vi.fn ()}
            originalCreatedBefore={null}
            setOriginalCreatedBefore={setBefore}/>,
    )

    const input = screen.getAllByDisplayValue ('')[0]
    fireEvent.blur (input, { target: { value: '2026-01-02T03:04' } })

    expect (setBefore).toHaveBeenCalledWith (expect.any (String))
  })

  it ('resets both values', () => {
    const setFrom = vi.fn ()
    const setBefore = vi.fn ()

    render (
        <PostOriginalCreatedTimeField
            originalCreatedFrom="2026-01-01T00:00:00Z"
            setOriginalCreatedFrom={setFrom}
            originalCreatedBefore="2026-01-02T00:00:00Z"
            setOriginalCreatedBefore={setBefore}/>,
    )

    const buttons = screen.getAllByRole ('button', { name: 'リセット' })
    fireEvent.click (buttons[0])
    fireEvent.click (buttons[1])

    expect (setFrom).toHaveBeenCalledWith (null)
    expect (setBefore).toHaveBeenCalledWith (null)
  })
})
