"""
Generate screen for the MiniMax TUI interface.

Provides an interactive interface for code generation with support for functions,
classes, tests, and project scaffolding with real-time preview and file output.
"""

import os
import asyncio
from typing import List, Dict, Any, Optional, Tuple
from pathlib import Path

try:
    from textual.app import ComposeResult
    from textual.screen import Screen
    from textual.widgets import (
        Header, Footer, Input, TextLog, Tree, Static, 
        Button, Horizontal, Vertical, TabbedContent, 
        TabPane, ProgressBar, Label, OptionList, 
        TextArea, Select, Checkbox, DataTable,
        DirectoryTree, Switch, RadioSet, RadioButton
    )
    from textual.containers import Container, ScrollableContainer
    from textual.reactive import reactive
    from textual.message import Message
    from textual.worker import Worker, get_current_worker
    from textual.binding import Binding
    from textual import work
    from rich.markdown import Markdown
    from rich.syntax import Syntax
    from rich.panel import Panel
    from rich.text import Text
    from rich.table import Table
    TEXTUAL_AVAILABLE = True
except ImportError:
    TEXTUAL_AVAILABLE = False
    # Fallback classes for when Textual is not available
    class Screen:
        pass
    class ComposeResult:
        pass
    class Message:
        pass


class GenerationStarted(Message):
    """Message for when code generation starts."""
    
    def __init__(self, generation_type: str, description: str) -> None:
        self.generation_type = generation_type
        self.description = description
        super().__init__()


class GenerationCompleted(Message):
    """Message for when code generation completes."""
    
    def __init__(self, result: str, success: bool = True) -> None:
        self.result = result
        self.success = success
        super().__init__()


class FileSelected(Message):
    """Message for when a file is selected for test generation."""
    
    def __init__(self, file_path: str) -> None:
        self.file_path = file_path
        super().__init__()


class GenerateScreen(Screen):
    """Interactive code generation screen for MiniMax TUI."""
    
    BINDINGS = [
        Binding("ctrl+c", "quit", "Quit"),
        Binding("ctrl+g", "generate", "Generate"),
        Binding("ctrl+s", "save", "Save"),
        Binding("ctrl+p", "preview", "Preview"),
        Binding("ctrl+n", "new_generation", "New"),
        Binding("ctrl+o", "open_file", "Open File"),
        Binding("f1", "show_help", "Help"),
        Binding("escape", "focus_description", "Focus Description"),
        Binding("f2", "toggle_preview", "Toggle Preview"),
        Binding("f3", "toggle_settings", "Toggle Settings"),
    ]
    
    CSS = """
    GenerateScreen {
        layout: grid;
        grid-size: 3 2;
        grid-columns: 1fr 1fr 300px;
        grid-rows: 1fr 40px;
    }
    
    #main_content {
        column-span: 2;
        row-span: 1;
        layout: vertical;
    }
    
    #settings_panel {
        column-span: 1;
        row-span: 1;
        background: $surface;
        border-left: solid $primary;
    }
    
    #status_bar {
        column-span: 3;
        row-span: 1;
        background: $surface-dark;
        border-top: solid $border;
        layout: horizontal;
        height: 3;
    }
    
    #generation_tabs {
        height: 1fr;
    }
    
    #input_panel {
        height: auto;
        min-height: 12;
        border: solid $accent;
        margin: 1 0;
    }
    
    #preview_panel {
        height: 1fr;
        border: solid $primary;
    }
    
    #generation_type_list {
        height: auto;
        max-height: 8;
        border: solid $accent;
        margin: 1 0;
    }
    
    #description_input {
        height: 6;
        border: solid $primary;
        margin: 1 0;
    }
    
    #language_select {
        width: 1fr;
        margin: 0 1;
    }
    
    #framework_select {
        width: 1fr;
        margin: 0 1;
    }
    
    #output_path_input {
        width: 1fr;
        margin: 0 1;
    }
    
    #generate_button {
        width: auto;
        min-width: 12;
        margin: 0 1;
    }
    
    #save_button {
        width: auto;
        min-width: 8;
        margin: 0 1;
    }
    
    #preview_log {
        height: 1fr;
        scrollbar-gutter: stable;
    }
    
    #project_files_table {
        height: 1fr;
        border: solid $accent;
    }
    
    #progress_container {
        height: auto;
        margin: 1 0;
    }
    
    #progress_bar {
        display: none;
    }
    
    #file_browser {
        height: 1fr;
        border: solid $accent;
        margin: 1 0;
    }
    
    .generation_option {
        padding: 1;
        margin: 0 1;
    }
    
    .setting_group {
        border: solid $border;
        margin: 1 0;
        padding: 1;
    }
    
    .status_item {
        padding: 0 1;
        color: $text-muted;
    }
    
    .success_status {
        color: $success;
    }
    
    .error_status {
        color: $error;
    }
    
    .warning_status {
        color: $warning;
    }
    
    .panel-title {
        background: $primary;
        color: $text-inverse;
        padding: 0 1;
        text-align: center;
        text-style: bold;
    }
    """
    
    def __init__(self, client=None, config=None, presenter=None, **kwargs):
        super().__init__(**kwargs)
        self.client = client
        self.config = config
        self.presenter = presenter
        
        # Generation state
        self.current_generation_type = "function"
        self.current_language = "python"
        self.current_framework = "auto"
        self.generated_content = ""
        self.project_files: List[Tuple[str, str]] = []
        self.selected_file_path = ""
        
        # UI state
        self.is_generating = reactive(False)
        self.preview_visible = reactive(True)
        self.settings_visible = reactive(True)
        self.current_worker: Optional[Worker] = None
        
        # Generation options
        self.generation_types = [
            ("function", "🔧 Function", "Generate a single function"),
            ("class", "🏗️ Class", "Generate a complete class"),
            ("test", "🧪 Tests", "Generate tests for existing code"),
            ("project", "📁 Project", "Scaffold a complete project")
        ]
        
        self.languages = [
            "python", "javascript", "typescript", "java", "cpp", "c", 
            "csharp", "go", "rust", "php", "ruby", "swift", "kotlin", 
            "scala", "shell", "sql"
        ]
        
        self.frameworks = {
            "python": ["auto", "pytest", "unittest", "nose2"],
            "javascript": ["auto", "jest", "mocha", "jasmine", "vitest"],
            "typescript": ["auto", "jest", "mocha", "vitest"],
            "java": ["auto", "junit", "testng", "spock"],
            "csharp": ["auto", "nunit", "xunit", "mstest"],
            "go": ["auto", "testing", "ginkgo", "testify"],
            "rust": ["auto", "cargo test", "rstest"],
            "php": ["auto", "phpunit", "pest", "codeception"],
            "ruby": ["auto", "rspec", "minitest", "test-unit"],
            "swift": ["auto", "xctest", "quick"],
            "kotlin": ["auto", "junit", "spek", "kotest"],
            "scala": ["auto", "scalatest", "specs2", "utest"]
        }
        
        # Import generate commands for actual generation
        try:
            from ...commands.generate import GenerateCommands
            self.generate_commands = GenerateCommands(client, config, presenter) if client else None
        except ImportError:
            self.generate_commands = None
    
    def compose(self) -> ComposeResult:
        """Compose the generate screen layout."""
        with TabbedContent(id="generation_tabs"):
            with TabPane("⚡ Generate", id="generate_tab"):
                with Container(id="main_content"):
                    # Generation type selection
                    yield Static("🎯 Generation Type", classes="panel-title")
                    yield OptionList(
                        *[(f"{icon} {name}", value) for value, icon, name in 
                          [(t[0], t[1].split()[0], t[1].split()[1]) for t in self.generation_types]],
                        id="generation_type_list"
                    )
                    
                    # Input panel
                    with Container(id="input_panel"):
                        yield Static("📝 Description", classes="panel-title")
                        yield TextArea(
                            placeholder="Describe what you want to generate...\n\nFor functions: 'Create a function that calculates fibonacci numbers'\nFor classes: 'Create a User class with authentication methods'\nFor tests: Select a file first\nFor projects: 'Create a REST API with user management'",
                            id="description_input"
                        )
                        
                        with Horizontal():
                            yield Button("⚡ Generate", id="generate_button", variant="primary")
                            yield Button("💾 Save", id="save_button", variant="success")
                            yield Button("👁️ Preview", id="preview_button", variant="default")
                    
                    # Progress indicator
                    with Container(id="progress_container"):
                        yield ProgressBar(
                            id="progress_bar",
                            show_eta=False,
                            show_percentage=False
                        )
                        yield Label("", id="progress_label")
                    
                    # Preview panel
                    with Container(id="preview_panel"):
                        yield Static("👁️ Preview", classes="panel-title")
                        yield TextLog(
                            id="preview_log",
                            highlight=True,
                            markup=True,
                            wrap=True,
                            auto_scroll=True
                        )
            
            with TabPane("📁 Project Files", id="project_tab"):
                yield DataTable(
                    id="project_files_table",
                    show_header=True,
                    show_row_labels=False,
                    zebra_stripes=True
                )
            
            with TabPane("📂 File Browser", id="browser_tab"):
                yield DirectoryTree("./", id="file_browser")
        
        # Settings panel
        with Container(id="settings_panel"):
            yield Static("⚙️ Settings", classes="panel-title")
            
            with Container(classes="setting_group"):
                yield Static("🔤 Language")
                yield Select(
                    [(lang.title(), lang) for lang in self.languages],
                    value="python",
                    id="language_select"
                )
            
            with Container(classes="setting_group"):
                yield Static("🧪 Test Framework")
                yield Select(
                    [("Auto-detect", "auto")],
                    value="auto",
                    id="framework_select"
                )
            
            with Container(classes="setting_group"):
                yield Static("📁 Output Path")
                yield Input(
                    placeholder="output.py",
                    id="output_path_input"
                )
            
            with Container(classes="setting_group"):
                yield Static("🔧 Options")
                yield Checkbox("Include tests", id="include_tests_checkbox")
                yield Checkbox("Include docs", id="include_docs_checkbox")
                yield Checkbox("Dry run", id="dry_run_checkbox")
        
        # Status bar
        with Container(id="status_bar"):
            yield Static("Ready", id="status_text", classes="status_item")
            yield Static("", id="generation_info", classes="status_item")
            yield Static("", id="file_info", classes="status_item")
    
    def on_mount(self) -> None:
        """Initialize the screen when mounted."""
        self.query_one("#description_input").focus()
        self._update_status("Ready to generate code")
        self._update_framework_options()
        self._setup_project_files_table()
        self._add_welcome_message()
    
    def _setup_project_files_table(self) -> None:
        """Setup the project files table."""
        table = self.query_one("#project_files_table", DataTable)
        table.add_columns("File", "Type", "Size", "Lines")
    
    def _add_welcome_message(self) -> None:
        """Add welcome message to preview."""
        preview_log = self.query_one("#preview_log", TextLog)
        
        welcome_panel = Panel(
            """🎉 Welcome to MiniMax Code Generator!

Select a generation type and describe what you want to create:

• **Function**: Generate individual functions with documentation
• **Class**: Create complete classes with methods and properties  
• **Tests**: Generate comprehensive test suites for existing code
• **Project**: Scaffold complete project structures

Configure your preferences in the settings panel and click Generate to start!""",
            title="⚡ Code Generator",
            title_align="left",
            border_style="blue",
            padding=(1, 2)
        )
        
        preview_log.write(welcome_panel)
        preview_log.write("")
    
    def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
        """Handle generation type selection."""
        if event.option_list.id == "generation_type_list":
            self.current_generation_type = event.option.id
            self._update_ui_for_generation_type()
            self._update_status(f"Selected: {event.option.prompt}")
    
    def on_select_changed(self, event: Select.Changed) -> None:
        """Handle select widget changes."""
        if event.select.id == "language_select":
            self.current_language = event.value
            self._update_framework_options()
            self._update_status(f"Language: {event.value.title()}")
        elif event.select.id == "framework_select":
            self.current_framework = event.value
            self._update_status(f"Framework: {event.value}")
    
    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "generate_button":
            self._start_generation()
        elif event.button.id == "save_button":
            self._save_generated_content()
        elif event.button.id == "preview_button":
            self._toggle_preview()
    
    def on_directory_tree_file_selected(self, event: DirectoryTree.FileSelected) -> None:
        """Handle file selection from directory tree."""
        if event.node.data and event.node.data.is_file():
            self.selected_file_path = str(event.node.data.path)
            self._update_file_info(self.selected_file_path)
            
            # If test generation is selected, update description
            if self.current_generation_type == "test":
                description_input = self.query_one("#description_input", TextArea)
                description_input.text = f"Generate comprehensive tests for: {self.selected_file_path}"
    
    def _update_ui_for_generation_type(self) -> None:
        """Update UI elements based on selected generation type."""
        description_input = self.query_one("#description_input", TextArea)
        
        placeholders = {
            "function": "Describe the function you want to create:\n\nExample: 'Create a function that calculates the factorial of a number using recursion. Include input validation and proper error handling.'",
            "class": "Describe the class you want to create:\n\nExample: 'Create a User class for a web application with properties for name, email, and password. Include methods for authentication, password hashing, and user validation.'",
            "test": "Select a file from the File Browser tab first, then describe any specific test requirements:\n\nExample: 'Focus on edge cases and error conditions. Include integration tests for database operations.'",
            "project": "Describe the project you want to scaffold:\n\nExample: 'Create a REST API project with user authentication, CRUD operations, database integration, and API documentation. Include Docker configuration and CI/CD setup.'"
        }
        
        description_input.placeholder = placeholders.get(self.current_generation_type, "Describe what you want to generate...")
        
        # Clear description for test generation to encourage file selection
        if self.current_generation_type == "test":
            description_input.text = ""
    
    def _update_framework_options(self) -> None:
        """Update framework options based on selected language."""
        framework_select = self.query_one("#framework_select", Select)
        frameworks = self.frameworks.get(self.current_language, ["auto"])
        
        framework_select.set_options([(f.title(), f) for f in frameworks])
        framework_select.value = "auto"
        self.current_framework = "auto"
    
    def _start_generation(self) -> None:
        """Start the code generation process."""
        if self.is_generating:
            self._update_status("Generation already in progress...")
            return
        
        description_input = self.query_one("#description_input", TextArea)
        description = description_input.text.strip()
        
        if not description and self.current_generation_type != "test":
            self._update_status("Please provide a description", "error")
            description_input.focus()
            return
        
        if self.current_generation_type == "test" and not self.selected_file_path:
            self._update_status("Please select a file for test generation", "error")
            return
        
        # Get options
        include_tests = self.query_one("#include_tests_checkbox", Checkbox).value
        include_docs = self.query_one("#include_docs_checkbox", Checkbox).value
        dry_run = self.query_one("#dry_run_checkbox", Checkbox).value
        output_path = self.query_one("#output_path_input", Input).value.strip()
        
        # Start generation
        self._generate_code(description, include_tests, include_docs, dry_run, output_path)
    
    @work(exclusive=True)
    async def _generate_code(self, description: str, include_tests: bool, include_docs: bool, dry_run: bool, output_path: str) -> None:
        """Generate code using the AI service."""
        try:
            self.is_generating = True
            self._show_progress(f"Generating {self.current_generation_type}...")
            
            if not self.generate_commands:
                # Mock generation for demo
                await self._mock_generation(description)
                return
            
            # Create args object for generate commands
            class Args:
                def __init__(self):
                    self.language = self.current_language
                    self.description = description
                    self.tests = include_tests
                    self.docs = include_docs
                    self.dry_run = dry_run
                    self.output = output_path
                    self.framework = self.current_framework if self.current_framework != "auto" else None
            
            args = Args()
            
            # Call appropriate generation method
            success = False
            if self.current_generation_type == "function":
                success = await asyncio.get_event_loop().run_in_executor(
                    None, self.generate_commands.function, args
                )
            elif self.current_generation_type == "class":
                success = await asyncio.get_event_loop().run_in_executor(
                    None, self.generate_commands.class_code, args
                )
            elif self.current_generation_type == "test":
                args.file = self.selected_file_path
                success = await asyncio.get_event_loop().run_in_executor(
                    None, self.generate_commands.test, args
                )
            elif self.current_generation_type == "project":
                args.name = output_path or "new_project"
                args.type = "library"  # Default project type
                success = await asyncio.get_event_loop().run_in_executor(
                    None, self.generate_commands.project, args
                )
            
            if success:
                self.call_from_thread(self._update_status, "Generation completed successfully!", "success")
            else:
                self.call_from_thread(self._update_status, "Generation failed", "error")
                
        except Exception as e:
            self.call_from_thread(self._update_status, f"Generation error: {str(e)}", "error")
            self.call_from_thread(self._add_error_to_preview, str(e))
        finally:
            self.is_generating = False
            self.call_from_thread(self._hide_progress)
    
    async def _mock_generation(self, description: str) -> None:
        """Mock generation for demo purposes."""
        await asyncio.sleep(1)  # Simulate processing time
        
        # Generate mock content based on type
        if self.current_generation_type == "function":
            content = self._generate_mock_function(description)
        elif self.current_generation_type == "class":
            content = self._generate_mock_class(description)
        elif self.current_generation_type == "test":
            content = self._generate_mock_test(description)
        elif self.current_generation_type == "project":
            content = self._generate_mock_project(description)
        else:
            content = f"# Generated {self.current_generation_type}\n\n# {description}\n\nprint('Hello, World!')"
        
        self.generated_content = content
        self.call_from_thread(self._display_generated_content, content)
        self.call_from_thread(self._update_status, "Mock generation completed!", "success")
    
    def _generate_mock_function(self, description: str) -> str:
        """Generate mock function content."""
        if self.current_language == "python":
            return f'''def generated_function(param1, param2=None):
    """
    {description}
    
    Args:
        param1: First parameter
        param2: Optional second parameter
        
    Returns:
        Result of the operation
    """
    # Implementation based on: {description}
    if param2 is None:
        param2 = "default"
    
    result = f"Processing {{param1}} with {{param2}}"
    return result


# Example usage
if __name__ == "__main__":
    result = generated_function("test", "value")
    print(result)
'''
        elif self.current_language == "javascript":
            return f'''/**
 * {description}
 * @param {{*}} param1 - First parameter
 * @param {{*}} param2 - Optional second parameter
 * @returns {{*}} Result of the operation
 */
function generatedFunction(param1, param2 = null) {{
    // Implementation based on: {description}
    if (param2 === null) {{
        param2 = "default";
    }}
    
    const result = `Processing ${{param1}} with ${{param2}}`;
    return result;
}}

// Example usage
const result = generatedFunction("test", "value");
console.log(result);
'''
        else:
            return f"// Generated {self.current_language} function\n// {description}\n\n// Implementation would go here"
    
    def _generate_mock_class(self, description: str) -> str:
        """Generate mock class content."""
        if self.current_language == "python":
            return f'''class GeneratedClass:
    """
    {description}
    """
    
    def __init__(self, name: str, value: int = 0):
        """
        Initialize the class.
        
        Args:
            name: Name identifier
            value: Initial value
        """
        self.name = name
        self.value = value
        self._private_data = {{}}
    
    def process(self, input_data):
        """
        Process input data according to requirements.
        
        Args:
            input_data: Data to process
            
        Returns:
            Processed result
        """
        # Implementation based on: {description}
        result = f"{{self.name}} processed {{input_data}}"
        self.value += 1
        return result
    
    def get_status(self):
        """Get current status of the object."""
        return {{
            "name": self.name,
            "value": self.value,
            "status": "active"
        }}
    
    def __str__(self):
        return f"GeneratedClass(name={{self.name}}, value={{self.value}})"


# Example usage
if __name__ == "__main__":
    obj = GeneratedClass("example", 10)
    result = obj.process("test data")
    print(result)
    print(obj.get_status())
'''
        elif self.current_language == "javascript":
            return f'''/**
 * {description}
 */
class GeneratedClass {{
    /**
     * Initialize the class.
     * @param {{string}} name - Name identifier
     * @param {{number}} value - Initial value
     */
    constructor(name, value = 0) {{
        this.name = name;
        this.value = value;
        this._privateData = {{}};
    }}
    
    /**
     * Process input data according to requirements.
     * @param {{*}} inputData - Data to process
     * @returns {{string}} Processed result
     */
    process(inputData) {{
        // Implementation based on: {description}
        const result = `${{this.name}} processed ${{inputData}}`;
        this.value += 1;
        return result;
    }}
    
    /**
     * Get current status of the object.
     * @returns {{Object}} Status information
     */
    getStatus() {{
        return {{
            name: this.name,
            value: this.value,
            status: "active"
        }};
    }}
    
    toString() {{
        return `GeneratedClass(name=${{this.name}}, value=${{this.value}})`;
    }}
}}

// Example usage
const obj = new GeneratedClass("example", 10);
const result = obj.process("test data");
console.log(result);
console.log(obj.getStatus());
'''
        else:
            return f"// Generated {self.current_language} class\n// {description}\n\n// Implementation would go here"
    
    def _generate_mock_test(self, description: str) -> str:
        """Generate mock test content."""
        if self.current_language == "python":
            return f'''import pytest
import unittest
from unittest.mock import Mock, patch

# Test file for: {self.selected_file_path}
# {description}


class TestGeneratedCode(unittest.TestCase):
    """Test cases for the generated code."""
    
    def setUp(self):
        """Set up test fixtures before each test method."""
        self.test_data = {{"key": "value", "number": 42}}
        self.mock_object = Mock()
    
    def test_basic_functionality(self):
        """Test basic functionality works as expected."""
        # Arrange
        expected_result = "expected"
        
        # Act
        # result = function_under_test(self.test_data)
        
        # Assert
        # self.assertEqual(result, expected_result)
        self.assertTrue(True)  # Placeholder
    
    def test_edge_cases(self):
        """Test edge cases and boundary conditions."""
        # Test empty input
        # result = function_under_test({{}})
        # self.assertIsNotNone(result)
        
        # Test None input
        # with self.assertRaises(ValueError):
        #     function_under_test(None)
        
        self.assertTrue(True)  # Placeholder
    
    def test_error_handling(self):
        """Test error handling and exception cases."""
        # Test invalid input types
        # with self.assertRaises(TypeError):
        #     function_under_test("invalid")
        
        self.assertTrue(True)  # Placeholder
    
    @patch('module.external_dependency')
    def test_with_mocks(self, mock_dependency):
        """Test functionality with mocked dependencies."""
        # Configure mock
        mock_dependency.return_value = "mocked_result"
        
        # Test with mock
        # result = function_under_test(self.test_data)
        # mock_dependency.assert_called_once()
        
        self.assertTrue(True)  # Placeholder


# Pytest-style tests
def test_pytest_example():
    """Example pytest test."""
    assert True


@pytest.mark.parametrize("input_value,expected", [
    ("test1", "result1"),
    ("test2", "result2"),
    ("test3", "result3"),
])
def test_parametrized(input_value, expected):
    """Test with multiple parameter sets."""
    # result = function_under_test(input_value)
    # assert result == expected
    assert True


if __name__ == "__main__":
    unittest.main()
'''
        elif self.current_language == "javascript":
            return f'''// Test file for: {self.selected_file_path}
// {description}

const {{ describe, it, expect, beforeEach, afterEach, jest }} = require('@jest/globals');

describe('Generated Code Tests', () => {{
    let testData;
    let mockObject;
    
    beforeEach(() => {{
        testData = {{ key: 'value', number: 42 }};
        mockObject = jest.fn();
    }});
    
    afterEach(() => {{
        jest.clearAllMocks();
    }});
    
    describe('Basic Functionality', () => {{
        it('should work with valid input', () => {{
            // Arrange
            const expectedResult = 'expected';
            
            // Act
            // const result = functionUnderTest(testData);
            
            // Assert
            // expect(result).toBe(expectedResult);
            expect(true).toBe(true); // Placeholder
        }});
        
        it('should handle empty input', () => {{
            // const result = functionUnderTest({{}});
            // expect(result).toBeDefined();
            expect(true).toBe(true); // Placeholder
        }});
    }});
    
    describe('Edge Cases', () => {{
        it('should handle null input', () => {{
            // expect(() => functionUnderTest(null)).toThrow();
            expect(true).toBe(true); // Placeholder
        }});
        
        it('should handle undefined input', () => {{
            // expect(() => functionUnderTest(undefined)).toThrow();
            expect(true).toBe(true); // Placeholder
        }});
    }});
    
    describe('Error Handling', () => {{
        it('should throw error for invalid input types', () => {{
            // expect(() => functionUnderTest('invalid')).toThrow(TypeError);
            expect(true).toBe(true); // Placeholder
        }});
    }});
    
    describe('Mocked Dependencies', () => {{
        it('should work with mocked external calls', () => {{
            // const mockDependency = jest.fn().mockReturnValue('mocked_result');
            // const result = functionUnderTest(testData);
            // expect(mockDependency).toHaveBeenCalledTimes(1);
            expect(true).toBe(true); // Placeholder
        }});
    }});
}});

// Parameterized tests
describe.each([
    ['test1', 'result1'],
    ['test2', 'result2'],
    ['test3', 'result3'],
])('Parameterized Tests', (inputValue, expected) => {{
    it(`should return ${{expected}} for input ${{inputValue}}`, () => {{
        // const result = functionUnderTest(inputValue);
        // expect(result).toBe(expected);
        expect(true).toBe(true); // Placeholder
    }});
}});
'''
        else:
            return f"// Generated {self.current_language} tests\n// {description}\n\n// Test implementation would go here"
    
    def _generate_mock_project(self, description: str) -> str:
        """Generate mock project structure."""
        # This would create project files and display them
        self.project_files = [
            ("README.md", f"# Generated Project\n\n{description}\n\n## Setup\n\n1. Install dependencies\n2. Run the application"),
            ("main.py", "#!/usr/bin/env python3\n\ndef main():\n    print('Hello, World!')\n\nif __name__ == '__main__':\n    main()"),
            ("requirements.txt", "# Project dependencies\nrequests>=2.25.0\nclick>=8.0.0"),
            (".gitignore", "# Python\n__pycache__/\n*.pyc\n*.pyo\n*.pyd\n.Python\nbuild/\ndevelop-eggs/"),
            ("tests/test_main.py", "import unittest\nfrom main import main\n\nclass TestMain(unittest.TestCase):\n    def test_main(self):\n        # Test main function\n        pass"),
            ("src/__init__.py", "# Package initialization"),
            ("config/settings.py", "# Application settings\nDEBUG = True\nVERSION = '1.0.0'")
        ]
        
        self._update_project_files_table()
        return f"Project scaffolded with {len(self.project_files)} files"
    
    def _display_generated_content(self, content: str) -> None:
        """Display generated content in the preview."""
        preview_log = self.query_one("#preview_log", TextLog)
        preview_log.clear()
        
        # Create syntax-highlighted content
        try:
            syntax = Syntax(
                content,
                self.current_language,
                theme="monokai",
                line_numbers=True,
                word_wrap=True
            )
            
            content_panel = Panel(
                syntax,
                title=f"⚡ Generated {self.current_generation_type.title()}",
                title_align="left",
                border_style="green",
                padding=(0, 1)
            )
            
            preview_log.write(content_panel)
            
        except Exception:
            # Fallback to plain text
            content_panel = Panel(
                content,
                title=f"⚡ Generated {self.current_generation_type.title()}",
                title_align="left",
                border_style="green",
                padding=(0, 1)
            )
            preview_log.write(content_panel)
        
        preview_log.write("")
        
        # Add generation info
        info_text = f"""📊 Generation Info:
• Type: {self.current_generation_type.title()}
• Language: {self.current_language.title()}
• Framework: {self.current_framework.title()}
• Lines: {content.count(chr(10)) + 1}
• Characters: {len(content)}"""
        
        info_panel = Panel(
            info_text,
            title="ℹ️ Details",
            title_align="left",
            border_style="blue",
            padding=(0, 1)
        )
        
        preview_log.write(info_panel)
    
    def _update_project_files_table(self) -> None:
        """Update the project files table."""
        table = self.query_one("#project_files_table", DataTable)
        table.clear()
        
        for file_path, content in self.project_files:
            file_type = self._get_file_type(file_path)
            size = f"{len(content)} chars"
            lines = str(content.count('\n') + 1)
            
            table.add_row(file_path, file_type, size, lines)
    
    def _get_file_type(self, file_path: str) -> str:
        """Get file type from extension."""
        ext = Path(file_path).suffix.lower()
        type_map = {
            '.py': 'Python',
            '.js': 'JavaScript',
            '.ts': 'TypeScript',
            '.md': 'Markdown',
            '.txt': 'Text',
            '.json': 'JSON',
            '.yaml': 'YAML',
            '.yml': 'YAML',
            '.toml': 'TOML',
            '.ini': 'Config',
            '.cfg': 'Config',
            '.gitignore': 'Git',
            '': 'Config'
        }
        return type_map.get(ext, 'Unknown')
    
    def _save_generated_content(self) -> None:
        """Save the generated content to file."""
        if not self.generated_content:
            self._update_status("No content to save", "warning")
            return
        
        output_path = self.query_one("#output_path_input", Input).value.strip()
        if not output_path:
            # Generate default filename
            ext_map = {
                'python': '.py',
                'javascript': '.js',
                'typescript': '.ts',
                'java': '.java',
                'cpp': '.cpp',
                'c': '.c',
                'csharp': '.cs',
                'go': '.go',
                'rust': '.rs',
                'php': '.php',
                'ruby': '.rb',
                'swift': '.swift',
                'kotlin': '.kt',
                'scala': '.scala',
                'shell': '.sh',
                'sql': '.sql'
            }
            ext = ext_map.get(self.current_language, '.txt')
            output_path = f"generated_{self.current_generation_type}{ext}"
        
        try:
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(self.generated_content)
            
            self._update_status(f"Saved to {output_path}", "success")
            
            # Add save confirmation to preview
            preview_log = self.query_one("#preview_log", TextLog)
            save_panel = Panel(
                f"✅ Content saved to: {output_path}",
                title="💾 Saved",
                title_align="left",
                border_style="green",
                padding=(0, 1)
            )
            preview_log.write(save_panel)
            
        except Exception as e:
            self._update_status(f"Save failed: {str(e)}", "error")
    
    def _add_error_to_preview(self, error_message: str) -> None:
        """Add error message to preview."""
        preview_log = self.query_one("#preview_log", TextLog)
        
        error_panel = Panel(
            f"❌ {error_message}",
            title="Error",
            title_align="left",
            border_style="red",
            padding=(0, 1)
        )
        
        preview_log.write(error_panel)
        preview_log.write("")
    
    def _show_progress(self, message: str) -> None:
        """Show progress indicator."""
        progress_bar = self.query_one("#progress_bar", ProgressBar)
        progress_label = self.query_one("#progress_label", Label)
        
        progress_bar.styles.display = "block"
        progress_label.update(message)
        progress_bar.advance(0)  # Start indeterminate progress
    
    def _hide_progress(self) -> None:
        """Hide progress indicator."""
        progress_bar = self.query_one("#progress_bar", ProgressBar)
        progress_label = self.query_one("#progress_label", Label)
        
        progress_bar.styles.display = "none"
        progress_label.update("")
    
    def _update_status(self, message: str, level: str = "info") -> None:
        """Update status bar message."""
        status_text = self.query_one("#status_text", Static)
        
        # Apply appropriate styling
        if level == "success":
            status_text.add_class("success_status")
            status_text.remove_class("error_status")
            status_text.remove_class("warning_status")
        elif level == "error":
            status_text.add_class("error_status")
            status_text.remove_class("success_status")
            status_text.remove_class("warning_status")
        elif level == "warning":
            status_text.add_class("warning_status")
            status_text.remove_class("success_status")
            status_text.remove_class("error_status")
        else:
            status_text.remove_class("success_status")
            status_text.remove_class("error_status")
            status_text.remove_class("warning_status")
        
        status_text.update(message)
    
    def _update_file_info(self, file_path: str) -> None:
        """Update file info in status bar."""
        file_info = self.query_one("#file_info", Static)
        
        try:
            stat = Path(file_path).stat()
            size = stat.st_size
            
            # Format size
            for unit in ['B', 'KB', 'MB', 'GB']:
                if size < 1024:
                    size_str = f"{size:.1f} {unit}"
                    break
                size /= 1024
            else:
                size_str = f"{size:.1f} TB"
            
            file_info.update(f"📁 {Path(file_path).name} ({size_str})")
            
        except Exception:
            file_info.update(f"📁 {Path(file_path).name}")
    
    def _toggle_preview(self) -> None:
        """Toggle preview panel visibility."""
        self.preview_visible = not self.preview_visible
        preview_panel = self.query_one("#preview_panel")
        
        if self.preview_visible:
            preview_panel.styles.display = "block"
        else:
            preview_panel.styles.display = "none"
    
    # Action handlers for key bindings
    def action_quit(self) -> None:
        """Quit the application."""
        self.app.exit()
    
    def action_generate(self) -> None:
        """Start generation."""
        self._start_generation()
    
    def action_save(self) -> None:
        """Save generated content."""
        self._save_generated_content()
    
    def action_preview(self) -> None:
        """Toggle preview."""
        self._toggle_preview()
    
    def action_new_generation(self) -> None:
        """Start new generation."""
        # Clear current content
        self.generated_content = ""
        self.project_files = []
        
        # Clear UI
        preview_log = self.query_one("#preview_log", TextLog)
        preview_log.clear()
        self._add_welcome_message()
        
        table = self.query_one("#project_files_table", DataTable)
        table.clear()
        
        # Reset inputs
        description_input = self.query_one("#description_input", TextArea)
        description_input.text = ""
        description_input.focus()
        
        output_path_input = self.query_one("#output_path_input", Input)
        output_path_input.value = ""
        
        self._update_status("Ready for new generation")
    
    def action_open_file(self) -> None:
        """Focus file browser."""
        # Switch to file browser tab
        tabs = self.query_one("#generation_tabs", TabbedContent)
        tabs.active = "browser_tab"
    
    def action_show_help(self) -> None:
        """Show help information."""
        preview_log = self.query_one("#preview_log", TextLog)
        
        help_text = """🔧 Generation Commands:
• **Function**: Generate individual functions with documentation
• **Class**: Create complete classes with methods and properties
• **Test**: Generate comprehensive test suites for existing code
• **Project**: Scaffold complete project structures with files

⌨️ Keyboard Shortcuts:
• Ctrl+G - Generate code
• Ctrl+S - Save generated content
• Ctrl+P - Toggle preview panel
• Ctrl+N - Start new generation
• Ctrl+O - Open file browser
• F1 - Show this help
• F2 - Toggle preview
• F3 - Toggle settings
• Esc - Focus description input

💡 Tips:
• Select generation type first, then provide description
• For tests, select a file from the File Browser tab
• Configure language and framework in settings
• Use descriptive prompts for better results
• Preview shows syntax-highlighted code
• Save automatically detects file extension"""
        
        help_panel = Panel(
            help_text,
            title="📖 Help - Code Generator",
            title_align="left",
            border_style="yellow",
            padding=(1, 2)
        )
        
        preview_log.write(help_panel)
        preview_log.write("")
    
    def action_focus_description(self) -> None:
        """Focus the description input."""
        self.query_one("#description_input").focus()
    
    def action_toggle_preview(self) -> None:
        """Toggle preview panel."""
        self._toggle_preview()
    
    def action_toggle_settings(self) -> None:
        """Toggle settings panel."""
        self.settings_visible = not self.settings_visible
        settings_panel = self.query_one("#settings_panel")
        
        if self.settings_visible:
            settings_panel.styles.display = "block"
        else:
            settings_panel.styles.display = "none"


# Fallback for when Textual is not available
if not TEXTUAL_AVAILABLE:
    class GenerateScreen:
        """Fallback GenerateScreen when Textual is not available."""
        
        def __init__(self, *args, **kwargs):
            raise ImportError(
                "Textual is required for TUI mode. Install with: pip install textual>=0.60"
            )