import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ModernChatInput } from './ModernChatInput';
import React from 'react';

// Mock sonner toast
vi.mock('sonner', () => ({
  toast: {
    info: vi.fn(),
  },
}));

describe('ModernChatInput', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('calls onChange when text is typed', () => {
    const onChange = vi.fn();
    render(<ModernChatInput value="" onChange={onChange} onSubmit={vi.fn()} />);

    const textarea = screen.getByPlaceholderText('Mande uma mensagem para o Xertica');
    fireEvent.change(textarea, { target: { value: 'hello' } });

    expect(onChange).toHaveBeenCalledWith('hello');
  });

  it('calls onSubmit when send button is clicked', () => {
    const onSubmit = vi.fn();
    render(<ModernChatInput value="hello" onChange={vi.fn()} onSubmit={onSubmit} />);

    const sendButton = screen.getByLabelText('Enviar mensagem');
    fireEvent.click(sendButton);

    expect(onSubmit).toHaveBeenCalled();
  });

  it('opens actions popover and selects an action', () => {
    render(<ModernChatInput value="" onChange={vi.fn()} onSubmit={vi.fn()} />);

    // Open popover
    fireEvent.click(screen.getByLabelText('Ver ações'));

    // Select document action
    const docAction = screen.getByText('Criar documento');
    fireEvent.click(docAction);

    // Check if action chip is visible
    expect(screen.getByText('Criar documento')).toBeInTheDocument();
  });

  it('handles voice recording simulation', async () => {
    const onVoiceRecording = vi.fn();
    render(
      <ModernChatInput
        value=""
        onChange={vi.fn()}
        onSubmit={vi.fn()}
        onVoiceRecording={onVoiceRecording}
      />
    );

    const micButton = screen.getByLabelText('Sugerir com voz');
    fireEvent.click(micButton);

    // Should show recording indicator
    expect(screen.getByText('Gravando áudio')).toBeInTheDocument();

    // Stop recording
    fireEvent.click(screen.getByText('Parar gravação'));

    expect(onVoiceRecording).toHaveBeenCalled();

    // Wait for the indicator to disappear
    await waitFor(() => {
      expect(screen.queryByText('Gravando áudio')).not.toBeInTheDocument();
    });
  });
});
