import React from 'react'
import { renderHook } from '@testing-library/react'
import { useFocusHandler } from './use-focus-handler'
import { GridProvider } from '../context/grid-context'
import { createStore } from '../state'
import type { GridFullApi } from '../api'
import { createApi } from '../api'

describe('useFocusHandler', () => {
    let store: ReturnType<typeof createStore>
    let api: GridFullApi

    beforeEach(() => {
        store = createStore()
        api = createApi(store, {} as any)
        jest.spyOn(store.selectors, 'selectHasFocus').mockReturnValue(false)
        jest.spyOn(api.focus, 'set')
    })

    it('should return hasFocus as false initially', () => {
        const { result } = renderHook(
            () => useFocusHandler('column-1', 'body', 'row-1'),
            {
                wrapper: ({ children }) => (
                    <GridProvider {...store} events={{} as any} api={api}>
                        {children}
                    </GridProvider>
                ),
            }
        )

        const [hasFocus] = result.current
        expect(hasFocus).toBe(false)
    })

    it('should call grid.api.focus.set when onFocus is triggered and focus is not set', () => {
        const { result } = renderHook(
            () => useFocusHandler('column-1', 'body', 'row-1'),
            {
                wrapper: ({ children }) => (
                    <GridProvider {...store} events={{} as any} api={api}>
                        {children}
                    </GridProvider>
                ),
            }
        )

        const [, onFocus] = result.current

        onFocus()

        expect(api.focus.set).toHaveBeenCalledWith('row-1', 'column-1', 'body')
    })

    it('should not call grid.api.focus.set when onFocus is triggered and focus is already set', () => {
        jest.spyOn(store.selectors, 'selectHasFocus').mockReturnValue(true)

        const { result } = renderHook(
            () => useFocusHandler('column-1', 'body', 'row-1'),
            {
                wrapper: ({ children }) => (
                    <GridProvider {...store} events={{} as any} api={api}>
                        {children}
                    </GridProvider>
                ),
            }
        )

        const [, onFocus] = result.current

        onFocus()

        expect(api.focus.set).not.toHaveBeenCalled()
    })
})
