import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createRef } from 'react'
import { Textarea } from './Textarea'

describe('Textarea', () => {
  it('renders a textarea element', () => {
    render(<Textarea placeholder="Enter text" />)
    expect(screen.getByPlaceholderText('Enter text')).toBeInTheDocument()
  })

  it('renders with default rows of 3', () => {
    render(<Textarea />)
    const el = screen.getByRole('textbox')
    expect(el).toHaveAttribute('rows', '3')
  })

  it('accepts a custom rows value', () => {
    render(<Textarea rows={5} />)
    expect(screen.getByRole('textbox')).toHaveAttribute('rows', '5')
  })

  it('accepts user input', async () => {
    const user = userEvent.setup()
    render(<Textarea />)
    const el = screen.getByRole('textbox')
    await user.type(el, 'hello world')
    expect(el).toHaveValue('hello world')
  })

  it('calls onChange when value changes', async () => {
    const onChange = vi.fn()
    const user = userEvent.setup()
    render(<Textarea onChange={onChange} />)
    await user.type(screen.getByRole('textbox'), 'a')
    expect(onChange).toHaveBeenCalled()
  })

  it('applies resize class for vertical (default)', () => {
    render(<Textarea />)
    const el = screen.getByRole('textbox')
    expect(el.className).toContain('resizeVertical')
  })

  it('applies resize class for none', () => {
    render(<Textarea resize="none" />)
    const el = screen.getByRole('textbox')
    expect(el.className).toContain('resizeNone')
  })

  it('applies resize class for horizontal', () => {
    render(<Textarea resize="horizontal" />)
    const el = screen.getByRole('textbox')
    expect(el.className).toContain('resizeHorizontal')
  })

  it('applies resize class for both', () => {
    render(<Textarea resize="both" />)
    const el = screen.getByRole('textbox')
    expect(el.className).toContain('resizeBoth')
  })

  it('forwards ref to the textarea element', () => {
    const ref = createRef<HTMLTextAreaElement>()
    render(<Textarea ref={ref} />)
    expect(ref.current).toBeInstanceOf(HTMLTextAreaElement)
  })

  it('passes additional props to the textarea', () => {
    render(<Textarea disabled data-testid="ta" />)
    expect(screen.getByTestId('ta')).toBeDisabled()
  })

  it('applies custom className', () => {
    render(<Textarea className="custom" />)
    expect(screen.getByRole('textbox').className).toContain('custom')
  })
})
