import pytest
from unittest.mock import MagicMock, patch
from PyQt6.QtCore import Qt
from dracula.ui import DraculaChatUI
from dracula import Dracula

# ==========================================
# 1. UI Test Configuration
# ==========================================


@pytest.fixture
def mock_ai():
    """Creates a mocked Dracula instance for UI testing."""
    ai = MagicMock(spec=Dracula)
    ai.chat.return_value = "This is a mocked UI response."
    return ai


@pytest.fixture
def app(qtbot, mock_ai):
    """Initializes the UI and provides it to the tests."""
    test_ui = DraculaChatUI(ai=mock_ai)
    qtbot.addWidget(test_ui)
    return test_ui


# ==========================================
# 2. UI Functional Tests
# ==========================================


def test_ui_initial_state(app):
    """Verify the UI starts with empty fields and correct titles."""
    assert app.windowTitle() == "Dracula AI Chat"
    assert app.input_field.text() == ""
    assert app.send_button.isEnabled() is True


def test_ui_send_message_flow(app, qtbot, mock_ai):
    """Simulate typing a message and clicking send."""
    test_msg = "Hello Dracula!"

    qtbot.keyClicks(app.input_field, test_msg)

    qtbot.mouseClick(app.send_button, Qt.MouseButton.LeftButton)

    qtbot.waitUntil(lambda: app.send_button.isEnabled(), timeout=5000)

    mock_ai.chat.assert_called_with(test_msg, filepath=None)
    assert "This is a mocked UI response." in app.chat_display.toHtml()
    assert app.input_field.text() == ""


def test_ui_attachment_selection(app, qtbot):
    """Test the file selection logic by mocking the QFileDialog."""
    fake_file = "C:/test_image.png"

    with patch(
        "PyQt6.QtWidgets.QFileDialog.getOpenFileName",
        return_value=(fake_file, "Selected"),
    ):
        qtbot.mouseClick(app.attach_button, Qt.MouseButton.LeftButton)

    assert app.selected_file_path == fake_file
    assert not app.file_label.isHidden()
    assert "test_image.png" in app.file_label.text()


def test_ui_clear_attachment(app, qtbot):
    """Test if clicking the file label clears the attachment."""
    app.selected_file_path = "some_file.jpg"
    app.file_label.setText("Attached file")
    app.file_label.setVisible(True)

    qtbot.mouseClick(app.file_label, Qt.MouseButton.LeftButton)

    assert app.selected_file_path is None
    assert app.file_label.isHidden()


def test_ui_theme_switching(qtbot, mock_ai):
    """Verify that light theme applies different colors."""
    light_ui = DraculaChatUI(ai=mock_ai, theme="light")
    qtbot.addWidget(light_ui)
    assert "#eff1f5" in light_ui.styleSheet()
