import React from 'react'
import { render } from '../utils/test-utils'
import type { GridEditorInputTimeProps } from './input-time'
import { GridEditorInputTime } from './input-time'
import userEvent from '@testing-library/user-event'

const baseProps = {
    rowId: '1',
    mode: 'editing' as GridEditorInputTimeProps<any>['mode'],
    tabIndex: 0,
    label: '',
    value: '1:23',
    columnId: 'name',
}

describe('GridEditorInputTime', () => {
    let onConfirm: jest.Mock
    let onCancel: jest.Mock

    beforeEach(() => {
        onConfirm = jest.fn()
        onCancel = jest.fn()
    })

    function renderInput(props: Partial<GridEditorInputTimeProps<any>> = {}) {
        return render(
            <GridEditorInputTime
                {...baseProps}
                onCancel={onCancel}
                onConfirm={onConfirm}
                {...props}
            />
        )
    }

    it('should render', () => {
        const { queryByRole } = renderInput()
        expect(queryByRole('textbox')).toBeInTheDocument()
    })

    it('should support editing (commit with Tab)', async () => {
        renderInput()

        await userEvent.keyboard('{Tab}2:34{Tab}')

        expect(onConfirm).toHaveBeenCalledWith('2:34', {
            continueEditing: 'next',
        })
    })

    it('should support editing (commit with Shift+Tab)', async () => {
        renderInput()

        await userEvent.keyboard('{Tab}2:34{Shift>}{Tab}{/Shift}')

        expect(onConfirm).toHaveBeenCalledWith('2:34', {
            continueEditing: 'previous',
        })
    })

    it('should support editing (commit with Enter)', async () => {
        renderInput()

        await userEvent.keyboard('{Tab}2:34{Enter}')

        expect(onConfirm).toHaveBeenCalledWith('2:34')
    })

    it('should support cancelling an edit with Esc', async () => {
        renderInput()

        await userEvent.keyboard('{Tab}2:34{Escape}')

        expect(onConfirm).not.toHaveBeenCalled()
        expect(onCancel).toHaveBeenCalled()
    })

    it('should support controlled rendering', async () => {
        const Wrapper = () => {
            const [value, setValue] = React.useState('')

            return (
                <GridEditorInputTime
                    {...baseProps}
                    value={value}
                    controlled
                    onChange={(val) =>
                        setValue(val.substring(0, 1).toLowerCase())
                    }
                    onCancel={onCancel}
                    onConfirm={onConfirm}
                />
            )
        }

        render(<Wrapper />)

        await userEvent.keyboard('{Tab}2:34{Tab}')

        expect(onConfirm).toHaveBeenCalledWith('2', {
            continueEditing: 'next',
        })
    })
})
