import { describe, it, expect, beforeEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { usePersistentFilters, defaultFilters, FilterState } from './usePersistentFilters'

// Mock localStorage
const localStorageMock = (() => {
    let store: Record<string, string> = {}
    return {
        getItem: vi.fn((key: string) => store[key] || null),
        setItem: vi.fn((key: string, value: string) => {
            store[key] = value
        }),
        removeItem: vi.fn((key: string) => {
            delete store[key]
        }),
        clear: vi.fn(() => {
            store = {}
        })
    }
})()

Object.defineProperty(window, 'localStorage', { value: localStorageMock })

describe('usePersistentFilters', () => {
    beforeEach(() => {
        localStorageMock.clear()
        vi.clearAllMocks()
    })

    it('should return default filters when localStorage is empty', () => {
        const { result } = renderHook(() => usePersistentFilters())

        expect(result.current.filters).toEqual(defaultFilters)
    })

    it('should load persisted filters from localStorage', () => {
        const persistedFilters: FilterState = {
            activeIngredient: 'Amoxicilina',
            category: 'Antibiótico',
            lab: 'EMS'
        }
        localStorageMock.getItem.mockReturnValueOnce(JSON.stringify(persistedFilters))

        const { result } = renderHook(() => usePersistentFilters())

        expect(result.current.filters).toEqual(persistedFilters)
    })

    it('should update filters and persist to localStorage', () => {
        const { result } = renderHook(() => usePersistentFilters())

        act(() => {
            result.current.setFilters({
                ...defaultFilters,
                activeIngredient: 'Dipirona'
            })
        })

        expect(result.current.filters.activeIngredient).toBe('Dipirona')
        expect(localStorageMock.setItem).toHaveBeenCalledWith(
            'mp-quick-filters',
            expect.stringContaining('Dipirona')
        )
    })

    it('should update individual filter fields', () => {
        const { result } = renderHook(() => usePersistentFilters())

        act(() => {
            result.current.setFilters((prev) => ({ ...prev, lab: 'Eurofarma' }))
        })

        expect(result.current.filters.lab).toBe('Eurofarma')
        expect(result.current.filters.activeIngredient).toBe('')
        expect(result.current.filters.category).toBe('')
    })

    it('should reset filters to defaults', () => {
        const { result } = renderHook(() => usePersistentFilters())

        act(() => {
            result.current.setFilters({
                activeIngredient: 'Test',
                category: 'Test',
                lab: 'Test'
            })
        })

        act(() => {
            result.current.setFilters(defaultFilters)
        })

        expect(result.current.filters).toEqual(defaultFilters)
    })
})
