import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, act } from '@testing-library/react'
import HomeView from './views/HomeView.jsx'
import SearchView from './views/SearchView.jsx'

beforeEach(() => {
  vi.useFakeTimers()
})

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

describe('HomeView', () => {
  it('renders two action buttons on the home screen', () => {
    const onSearch = vi.fn()
    const onScan = vi.fn()
    render(<HomeView onSearchClick={onSearch} onScanClick={onScan} />)
    expect(screen.getByRole('button', { name: /buscar medicamento/i })).toBeInTheDocument()
    expect(screen.getByRole('button', { name: /escanear tsi/i })).toBeInTheDocument()
  })

  it('calls onSearchClick when Buscar Medicamento is clicked', async () => {
    const onSearch = vi.fn()
    render(<HomeView onSearchClick={onSearch} onScanClick={vi.fn()} />)
    fireEvent.click(screen.getByRole('button', { name: /buscar medicamento/i }))
    expect(onSearch).toHaveBeenCalledTimes(1)
  })
})

describe('SearchView', () => {
  it('renders search bar with placeholder', () => {
    render(<SearchView />)
    expect(screen.getByPlaceholderText(/escriba el nombre del medicamento/i)).toBeInTheDocument()
  })

  it('does not fetch for queries shorter than 2 chars', async () => {
    const fetchMock = vi.spyOn(globalThis, 'fetch')
    render(<SearchView />)

    fireEvent.change(screen.getByPlaceholderText(/escriba el nombre del medicamento/i), {
      target: { value: 'a' },
    })

    await act(async () => {
      await vi.runAllTimersAsync()
    })

    expect(fetchMock).not.toHaveBeenCalled()
  })

  it('fetches and displays results for valid query', async () => {
    const medicines = [
      { id: 'REG001', name: 'Ibuprofeno 400mg', active_ingredient: 'Ibuprofeno', dosage: '400mg', form: 'Comprimido' },
    ]
    vi.spyOn(globalThis, 'fetch').mockResolvedValue({
      ok: true,
      json: async () => medicines,
    })

    render(<SearchView />)

    fireEvent.change(screen.getByPlaceholderText(/escriba el nombre del medicamento/i), {
      target: { value: 'ibu' },
    })

    await act(async () => {
      await vi.runAllTimersAsync()
    })

    expect(screen.getByText('Ibuprofeno 400mg')).toBeInTheDocument()
  })

  it('clears results when query is cleared after a search', async () => {
    const medicines = [
      { id: 'REG001', name: 'Ibuprofeno 400mg', active_ingredient: 'Ibuprofeno', dosage: '400mg', form: 'Comprimido' },
    ]
    vi.spyOn(globalThis, 'fetch').mockResolvedValue({
      ok: true,
      json: async () => medicines,
    })

    render(<SearchView />)
    const input = screen.getByPlaceholderText(/escriba el nombre del medicamento/i)

    fireEvent.change(input, { target: { value: 'ibu' } })
    await act(async () => { await vi.runAllTimersAsync() })
    expect(screen.getByText('Ibuprofeno 400mg')).toBeInTheDocument()

    fireEvent.change(input, { target: { value: '' } })
    await act(async () => { await vi.runAllTimersAsync() })

    expect(screen.queryByText('Ibuprofeno 400mg')).not.toBeInTheDocument()
  })
})
