"""
Analyze screen for the MiniMax TUI interface.

Provides an interactive code analysis interface with file selection, analysis type selection,
and rich results display. Supports review, explain, debug, and optimize operations.
"""

import os
import asyncio
from typing import List, Dict, Any, Optional, Union
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, DirectoryTree,
        OptionList, DataTable, Select, Checkbox,
        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:
        def __init__(self, *args, **kwargs):
            pass
    class Binding:
        def __init__(self, *args, **kwargs):
            pass
    class Button:
        def __init__(self, *args, **kwargs):
            pass
    class Input:
        def __init__(self, *args, **kwargs):
            pass
    class Static:
        def __init__(self, *args, **kwargs):
            pass
    class Container:
        def __init__(self, *args, **kwargs):
            pass
    class ProgressBar:
        def __init__(self, *args, **kwargs):
            pass
    class TabbedContent:
        def __init__(self, *args, **kwargs):
            pass
    class TabPane:
        def __init__(self, *args, **kwargs):
            pass
    class DirectoryTree:
        def __init__(self, *args, **kwargs):
            pass
    class DataTable:
        def __init__(self, *args, **kwargs):
            pass
    class Select:
        def __init__(self, *args, **kwargs):
            pass
    class RadioSet:
        def __init__(self, *args, **kwargs):
            pass
    class RadioButton:
        def __init__(self, *args, **kwargs):
            pass
    class OptionList:
        def __init__(self, *args, **kwargs):
            pass
    class Checkbox:
        def __init__(self, *args, **kwargs):
            pass
    def reactive(default, **kwargs):
        return default
    def work(*args, **kwargs):
        def decorator(func):
            return func
        return decorator
    class Worker:
        def __init__(self, *args, **kwargs):
            pass
    def get_current_worker():
        return None

from ..theme import get_theme_config, get_icon, get_color


class AnalysisStarted(Message):
    """Message for when analysis starts."""
    
    def __init__(self, analysis_type: str, files: List[str]) -> None:
        self.analysis_type = analysis_type
        self.files = files
        super().__init__()


class AnalysisCompleted(Message):
    """Message for when analysis completes."""
    
    def __init__(self, analysis_type: str, results: Dict[str, Any]) -> None:
        self.analysis_type = analysis_type
        self.results = results
        super().__init__()


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


class AnalyzeScreen(Screen):
    """Interactive code analysis screen for MiniMax TUI."""
    
    BINDINGS = [
        Binding("ctrl+c", "quit", "Quit"),
        Binding("ctrl+n", "new_analysis", "New Analysis"),
        Binding("ctrl+o", "open_file", "Open File"),
        Binding("ctrl+r", "run_analysis", "Run Analysis"),
        Binding("ctrl+s", "save_results", "Save Results"),
        Binding("ctrl+l", "clear_results", "Clear Results"),
        Binding("f1", "show_help", "Help"),
        Binding("f2", "toggle_file_panel", "Toggle Files"),
        Binding("f3", "toggle_config_panel", "Toggle Config"),
        Binding("escape", "focus_files", "Focus Files"),
        Binding("tab", "next_tab", "Next Tab"),
        Binding("shift+tab", "prev_tab", "Previous Tab"),
    ]
    
    CSS = """
    AnalyzeScreen {
        layout: grid;
        grid-size: 4 3;
        grid-columns: 300px 1fr 300px;
        grid-rows: auto 1fr auto;
    }
    
    #header_container {
        column-span: 3;
        row-span: 1;
        height: auto;
        background: $surface;
        border-bottom: solid $primary;
    }
    
    #file_panel {
        column-span: 1;
        row-span: 1;
        background: $surface;
        border-right: solid $border;
    }
    
    #main_content {
        column-span: 1;
        row-span: 1;
        layout: vertical;
    }
    
    #config_panel {
        column-span: 1;
        row-span: 1;
        background: $surface;
        border-left: solid $border;
    }
    
    #status_bar {
        column-span: 3;
        row-span: 1;
        height: auto;
        background: $surface;
        border-top: solid $border;
    }
    
    #file_tree {
        height: 1fr;
        border: solid $accent;
        scrollbar-gutter: stable;
    }
    
    #selected_files {
        height: auto;
        max-height: 8;
        border: solid $primary;
        margin: 1 0;
    }
    
    #analysis_tabs {
        height: 1fr;
    }
    
    #results_log {
        height: 1fr;
        border: solid $primary;
        scrollbar-gutter: stable;
    }
    
    #results_table {
        height: 1fr;
        border: solid $accent;
    }
    
    #code_viewer {
        height: 1fr;
        border: solid $success;
    }
    
    #analysis_options {
        height: auto;
        border: solid $accent;
        margin: 1 0;
        padding: 1;
    }
    
    #analysis_controls {
        height: auto;
        layout: horizontal;
        margin: 1 0;
    }
    
    #run_button {
        width: auto;
        min-width: 12;
        margin-right: 1;
    }
    
    #clear_button {
        width: auto;
        min-width: 10;
        margin-right: 1;
    }
    
    #save_button {
        width: auto;
        min-width: 10;
    }
    
    #progress_container {
        height: auto;
        margin: 1 0;
    }
    
    #progress_bar {
        display: none;
    }
    
    #analysis_type_select {
        margin: 1 0;
    }
    
    #focus_input {
        margin: 1 0;
    }
    
    #target_input {
        margin: 1 0;
    }
    
    #error_input {
        margin: 1 0;
    }
    
    #context_input {
        margin: 1 0;
    }
    
    .panel-title {
        background: $primary;
        color: $text-inverse;
        padding: 0 1;
        text-align: center;
        text-style: bold;
    }
    
    .file-item {
        padding: 0 1;
        margin: 0;
    }
    
    .file-item:hover {
        background: $accent 20%;
    }
    
    .selected-file {
        background: $primary 30%;
        border-left: solid $primary;
    }
    
    .analysis-result {
        padding: 1;
        margin: 1 0;
        border-left: solid $accent;
    }
    
    .error-result {
        background: $error 20%;
        border-left: solid $error;
    }
    
    .success-result {
        background: $success 20%;
        border-left: solid $success;
    }
    
    .warning-result {
        background: $warning 20%;
        border-left: solid $warning;
    }
    
    .info-result {
        background: $info 20%;
        border-left: solid $info;
    }
    """
    
    def __init__(self, client=None, config=None, analyze_commands=None, **kwargs):
        super().__init__(**kwargs)
        self.client = client
        self.config = config
        self.analyze_commands = analyze_commands
        self.selected_files: List[str] = []
        self.analysis_results: Dict[str, Any] = {}
        self.current_analysis_type = "review"
        self.is_analyzing = reactive(False)
        self.theme = get_theme_config()
        
        # Analysis configuration
        self.analysis_config = {
            "focus": "",
            "target": "",
            "error_message": "",
            "context": "",
            "function_name": "",
            "line_range": ""
        }
    
    def compose(self) -> ComposeResult:
        """Compose the analyze screen layout."""
        # Header
        with Container(id="header_container"):
            yield Static(f"{get_icon('analyze')} Code Analysis", classes="panel-title")
        
        # File selection panel
        with Container(id="file_panel"):
            yield Static(f"{get_icon('folder')} File Selection", classes="panel-title")
            yield DirectoryTree("./", id="file_tree")
            
            with Container(id="selected_files"):
                yield Static("📋 Selected Files (0)", id="selected_files_title")
                yield TextLog(
                    id="selected_files_log",
                    highlight=False,
                    markup=True,
                    wrap=False,
                    auto_scroll=True
                )
        
        # Main content area with tabs
        with Container(id="main_content"):
            with TabbedContent(id="analysis_tabs"):
                with TabPane("📊 Results", id="results_tab"):
                    yield TextLog(
                        id="results_log",
                        highlight=True,
                        markup=True,
                        wrap=True,
                        auto_scroll=True
                    )
                
                with TabPane("📋 Table", id="table_tab"):
                    yield DataTable(id="results_table", show_cursor=True)
                
                with TabPane("💻 Code", id="code_tab"):
                    yield TextLog(
                        id="code_viewer",
                        highlight=True,
                        markup=True,
                        wrap=False,
                        auto_scroll=False
                    )
            
            with Container(id="progress_container"):
                yield ProgressBar(
                    id="progress_bar",
                    show_eta=True,
                    show_percentage=True
                )
                yield Label("", id="progress_label")
        
        # Configuration panel
        with Container(id="config_panel"):
            yield Static(f"{get_icon('settings')} Analysis Configuration", classes="panel-title")
            
            with Container(id="analysis_options"):
                yield Label("Analysis Type:")
                yield Select(
                    [
                        ("🔍 Review", "review"),
                        ("📖 Explain", "explain"),
                        ("🐛 Debug", "debug"),
                        ("⚡ Optimize", "optimize")
                    ],
                    value="review",
                    id="analysis_type_select"
                )
                
                yield Label("Focus (for review):")
                yield Input(
                    placeholder="e.g., security, performance, style",
                    id="focus_input"
                )
                
                yield Label("Target (for optimization):")
                yield Input(
                    placeholder="e.g., performance, readability",
                    id="target_input"
                )
                
                yield Label("Error Message (for debug):")
                yield Input(
                    placeholder="Error message or description",
                    id="error_input"
                )
                
                yield Label("Context (for debug):")
                yield Input(
                    placeholder="Additional context information",
                    id="context_input"
                )
                
                yield Label("Function Name (for explain):")
                yield Input(
                    placeholder="Specific function to explain",
                    id="function_input"
                )
                
                yield Label("Line Range (for explain):")
                yield Input(
                    placeholder="e.g., 10-20",
                    id="lines_input"
                )
            
            with Horizontal(id="analysis_controls"):
                yield Button("🚀 Run Analysis", id="run_button", variant="primary")
                yield Button("🗑️ Clear", id="clear_button", variant="warning")
                yield Button("💾 Save", id="save_button", variant="success")
        
        # Status bar
        with Container(id="status_bar"):
            yield Static("Ready for analysis", id="status_text")
    
    def on_mount(self) -> None:
        """Initialize the screen when mounted."""
        self._update_status("Ready for analysis")
        self._add_system_message("🔍 MiniMax Code Analysis Interface")
        self._add_system_message("Select files from the tree, configure analysis options, and run analysis")
        self._add_system_message("Use F1 for help, F2/F3 to toggle panels")
        
        # Initialize results table
        self._setup_results_table()
    
    def on_directory_tree_file_selected(self, event) -> None:
        """Handle file selection from directory tree."""
        file_path = str(event.path)
        
        # Check if it's a code file
        if self._is_code_file(file_path):
            if file_path not in self.selected_files:
                self.selected_files.append(file_path)
                self._update_selected_files_display()
                self._update_status(f"Added {os.path.basename(file_path)} to selection")
            else:
                self._update_status(f"{os.path.basename(file_path)} already selected")
        else:
            self._update_status(f"Skipped non-code file: {os.path.basename(file_path)}")
    
    def on_select_changed(self, event) -> None:
        """Handle analysis type selection change."""
        if event.select.id == "analysis_type_select":
            self.current_analysis_type = event.value
            self._update_config_visibility()
            self._update_status(f"Analysis type changed to: {event.value}")

    def on_button_pressed(self, event) -> None:
        """Handle button presses."""
        if event.button.id == "run_button":
            self._run_analysis()
        elif event.button.id == "clear_button":
            self._clear_results()
        elif event.button.id == "save_button":
            self._save_results()

    def on_input_changed(self, event) -> None:
        """Handle input field changes."""
        input_id = event.input.id
        value = event.value
        
        if input_id == "focus_input":
            self.analysis_config["focus"] = value
        elif input_id == "target_input":
            self.analysis_config["target"] = value
        elif input_id == "error_input":
            self.analysis_config["error_message"] = value
        elif input_id == "context_input":
            self.analysis_config["context"] = value
        elif input_id == "function_input":
            self.analysis_config["function_name"] = value
        elif input_id == "lines_input":
            self.analysis_config["line_range"] = value
    
    def on_data_table_row_selected(self, event) -> None:
        """Handle table row selection."""
        table = self.query_one("#results_table", DataTable)
        row_key = event.row_key
        
        # Get row data and show details
        try:
            row_data = table.get_row(row_key)
            if row_data:
                self._show_result_details(row_data)
        except Exception as e:
            self._update_status(f"Error showing details: {str(e)}")
    
    def _setup_results_table(self) -> None:
        """Setup the results table with appropriate columns."""
        table = self.query_one("#results_table", DataTable)
        
        # Default columns for review results
        table.add_columns("File", "Issue", "Severity", "Line", "Description")
        table.cursor_type = "row"
        table.zebra_stripes = True
    
    def _update_config_visibility(self) -> None:
        """Update visibility of configuration options based on analysis type."""
        # This would show/hide relevant config options based on analysis type
        # For now, we'll just update the status
        config_hints = {
            "review": "Configure focus areas for code review",
            "explain": "Specify function name or line range to explain",
            "debug": "Provide error message and context for debugging",
            "optimize": "Set optimization target (performance, readability, etc.)"
        }
        
        hint = config_hints.get(self.current_analysis_type, "Configure analysis options")
        self._update_status(hint)
    
    def _is_code_file(self, file_path: str) -> bool:
        """Check if a file is a code file based on extension."""
        code_extensions = {
            '.py', '.js', '.ts', '.jsx', '.tsx', '.java', '.cpp', '.c', '.h', '.hpp',
            '.cs', '.php', '.rb', '.go', '.rs', '.swift', '.kt', '.scala', '.sh',
            '.bash', '.zsh', '.fish', '.ps1', '.html', '.css', '.scss', '.sass',
            '.less', '.xml', '.json', '.yaml', '.yml', '.toml', '.ini', '.cfg',
            '.conf', '.md', '.sql', '.r', '.R', '.m', '.pl', '.lua', '.vim'
        }
        
        return Path(file_path).suffix.lower() in code_extensions
    
    def _update_selected_files_display(self) -> None:
        """Update the selected files display."""
        files_log = self.query_one("#selected_files_log", TextLog)
        title = self.query_one("#selected_files_title", Static)
        
        # Update title
        count = len(self.selected_files)
        title.update(f"📋 Selected Files ({count})")
        
        # Clear and repopulate log
        files_log.clear()
        
        if not self.selected_files:
            files_log.write(Text("No files selected", style="dim"))
            return
        
        for i, file_path in enumerate(self.selected_files, 1):
            file_name = os.path.basename(file_path)
            file_icon = self.theme.get_file_icon(file_name)
            
            # Create clickable file entry
            file_text = Text()
            file_text.append(f"{i}. {file_icon} ", style="bold")
            file_text.append(file_name, style="blue")
            file_text.append(f" ({os.path.dirname(file_path)})", style="dim")
            
            files_log.write(file_text)
    
    def _run_analysis(self) -> None:
        """Run the selected analysis on selected files."""
        if not self.selected_files:
            self._update_status("❌ No files selected for analysis")
            return
        
        if not self.analyze_commands:
            self._update_status("❌ Analysis commands not available")
            return
        
        # Start analysis in worker
        self._start_analysis_worker()
    
    @work(exclusive=True)
    async def _start_analysis_worker(self) -> None:
        """Run analysis in a worker thread."""
        try:
            self.is_analyzing = True
            self._show_progress(f"Running {self.current_analysis_type} analysis...")
            
            # Create mock args object for analyze commands
            class MockArgs:
                def __init__(self, analysis_type: str, files: List[str], config: Dict[str, str]):
                    self.files = files
                    self.file = files[0] if files else ""
                    self.focus = config.get("focus", "")
                    self.target = config.get("target", "")
                    self.error = config.get("error_message", "")
                    self.context = config.get("context", "")
                    self.function = config.get("function_name", "")
                    self.lines = config.get("line_range", "")
            
            args = MockArgs(self.current_analysis_type, self.selected_files, self.analysis_config)
            
            # Run the appropriate analysis
            success = False
            if self.current_analysis_type == "review":
                success = await self._run_in_thread(self.analyze_commands.review, args)
            elif self.current_analysis_type == "explain":
                success = await self._run_in_thread(self.analyze_commands.explain, args)
            elif self.current_analysis_type == "debug":
                success = await self._run_in_thread(self.analyze_commands.debug, args)
            elif self.current_analysis_type == "optimize":
                success = await self._run_in_thread(self.analyze_commands.optimize, args)
            
            if success:
                self.call_from_thread(self._update_status, f"✅ {self.current_analysis_type.title()} analysis completed")
                self.call_from_thread(self._add_success_message, f"Analysis completed successfully")
            else:
                self.call_from_thread(self._update_status, f"❌ {self.current_analysis_type.title()} analysis failed")
                self.call_from_thread(self._add_error_message, f"Analysis failed to complete")
                
        except Exception as e:
            self.call_from_thread(self._update_status, f"❌ Analysis error: {str(e)}")
            self.call_from_thread(self._add_error_message, f"Analysis error: {str(e)}")
        finally:
            self.is_analyzing = False
            self.call_from_thread(self._hide_progress)
    
    async def _run_in_thread(self, func, args) -> bool:
        """Run a function in a thread and return success status."""
        try:
            # Simulate analysis work
            await asyncio.sleep(1)
            
            # In a real implementation, this would call the actual analyze command
            # For now, we'll simulate the results
            self.call_from_thread(self._simulate_analysis_results, self.current_analysis_type)
            return True
        except Exception:
            return False
    
    def _simulate_analysis_results(self, analysis_type: str) -> None:
        """Simulate analysis results for demonstration."""
        results_log = self.query_one("#results_log", TextLog)
        
        if analysis_type == "review":
            # Simulate review results
            results_log.write(Panel(
                "## 📋 Code Review Results\n\n"
                "### ✅ Strengths\n"
                "- Good code structure and organization\n"
                "- Proper error handling in most functions\n"
                "- Clear variable naming conventions\n\n"
                "### ⚠️ Areas for Improvement\n"
                "- Missing docstrings in some functions\n"
                "- Could benefit from type hints\n"
                "- Some functions are quite long and could be refactored\n\n"
                "### 🔒 Security Considerations\n"
                "- Input validation looks good\n"
                "- No obvious security vulnerabilities found\n\n"
                "### 🚀 Performance Opportunities\n"
                "- Consider using list comprehensions where appropriate\n"
                "- Some loops could be optimized",
                title="🔍 Review Summary",
                border_style="blue"
            ))
            
            # Add to table
            self._add_table_results([
                ["file1.py", "Missing docstring", "Medium", "15", "Function needs documentation"],
                ["file1.py", "Long function", "Low", "45", "Consider breaking into smaller functions"],
                ["file2.py", "No type hints", "Low", "8", "Add type annotations for better code clarity"]
            ])
            
        elif analysis_type == "explain":
            # Simulate explanation results
            results_log.write(Panel(
                "## 📖 Code Explanation\n\n"
                "### Overview\n"
                "This code implements a file processing utility that reads, processes, and writes data.\n\n"
                "### Key Components\n"
                "- **FileProcessor class**: Main processing logic\n"
                "- **read_file()**: Handles file input with error checking\n"
                "- **process_data()**: Core data transformation logic\n"
                "- **write_output()**: Saves processed results\n\n"
                "### How It Works\n"
                "1. The FileProcessor is initialized with configuration\n"
                "2. Input files are read and validated\n"
                "3. Data is processed according to specified rules\n"
                "4. Results are written to output files\n\n"
                "### Code Flow\n"
                "```python\n"
                "processor = FileProcessor(config)\n"
                "data = processor.read_file(input_path)\n"
                "result = processor.process_data(data)\n"
                "processor.write_output(result, output_path)\n"
                "```",
                title="📖 Code Explanation",
                border_style="green"
            ))
            
        elif analysis_type == "debug":
            # Simulate debug results
            results_log.write(Panel(
                "## 🐛 Debug Analysis\n\n"
                "### Issue Identified\n"
                "The error appears to be caused by a null reference exception on line 23.\n\n"
                "### Root Cause\n"
                "The variable `data` is not being properly initialized before use.\n\n"
                "### Proposed Solution\n"
                "```python\n"
                "# Before (problematic)\n"
                "if condition:\n"
                "    data = load_data()\n"
                "process(data)  # data might be undefined\n\n"
                "# After (fixed)\n"
                "data = None\n"
                "if condition:\n"
                "    data = load_data()\n"
                "if data is not None:\n"
                "    process(data)\n"
                "```\n\n"
                "### Prevention\n"
                "- Always initialize variables before use\n"
                "- Add null checks before processing\n"
                "- Consider using default values",
                title="🐛 Debug Analysis",
                border_style="red"
            ))
            
        elif analysis_type == "optimize":
            # Simulate optimization results
            results_log.write(Panel(
                "## ⚡ Optimization Analysis\n\n"
                "### Current Performance\n"
                "The code has several optimization opportunities for better performance.\n\n"
                "### Optimization Opportunities\n"
                "1. **Loop Optimization**: Replace nested loops with list comprehensions\n"
                "2. **Memory Usage**: Use generators instead of creating large lists\n"
                "3. **Algorithm Efficiency**: Consider using more efficient data structures\n\n"
                "### Optimized Code Example\n"
                "```python\n"
                "# Before (slower)\n"
                "result = []\n"
                "for item in data:\n"
                "    if condition(item):\n"
                "        result.append(transform(item))\n\n"
                "# After (faster)\n"
                "result = [transform(item) for item in data if condition(item)]\n"
                "```\n\n"
                "### Expected Benefits\n"
                "- 30-50% performance improvement\n"
                "- Reduced memory usage\n"
                "- More readable code",
                title="⚡ Optimization Results",
                border_style="yellow"
            ))
    
    def _add_table_results(self, rows: List[List[str]]) -> None:
        """Add results to the data table."""
        table = self.query_one("#results_table", DataTable)
        
        # Clear existing rows
        table.clear()
        
        # Add new rows
        for row in rows:
            table.add_row(*row)
    
    def _show_result_details(self, row_data: List[str]) -> None:
        """Show detailed information for a selected result."""
        code_viewer = self.query_one("#code_viewer", TextLog)
        code_viewer.clear()
        
        # Show details of the selected issue/result
        if len(row_data) >= 5:
            file_name, issue, severity, line, description = row_data[:5]
            
            detail_panel = Panel(
                f"**File:** {file_name}\n"
                f"**Issue:** {issue}\n"
                f"**Severity:** {severity}\n"
                f"**Line:** {line}\n"
                f"**Description:** {description}\n\n"
                f"**Suggested Action:**\n"
                f"Review the code at line {line} and consider the following improvements...",
                title=f"📋 Issue Details: {issue}",
                border_style="cyan"
            )
            
            code_viewer.write(detail_panel)
    
    def _clear_results(self) -> None:
        """Clear all analysis results."""
        # Clear results log
        results_log = self.query_one("#results_log", TextLog)
        results_log.clear()
        
        # Clear table
        table = self.query_one("#results_table", DataTable)
        table.clear()
        
        # Clear code viewer
        code_viewer = self.query_one("#code_viewer", TextLog)
        code_viewer.clear()
        
        # Reset results
        self.analysis_results.clear()
        
        self._add_system_message("🗑️ Analysis results cleared")
        self._update_status("Results cleared")
    
    def _save_results(self) -> None:
        """Save analysis results to file."""
        if not self.analysis_results:
            self._update_status("❌ No results to save")
            return
        
        # In a real implementation, this would open a file dialog
        # For now, just show a message
        self._add_success_message("💾 Results saved to analysis_results.md")
        self._update_status("Results saved successfully")
    
    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) -> None:
        """Update the status bar."""
        status_text = self.query_one("#status_text", Static)
        status_text.update(message)
    
    def _add_system_message(self, message: str) -> None:
        """Add a system message to the results log."""
        results_log = self.query_one("#results_log", TextLog)
        system_text = Text(f"ℹ️ {message}", style="dim cyan")
        results_log.write(system_text)
    
    def _add_success_message(self, message: str) -> None:
        """Add a success message to the results log."""
        results_log = self.query_one("#results_log", TextLog)
        success_text = Text(f"✅ {message}", style="bold green")
        results_log.write(success_text)
    
    def _add_error_message(self, message: str) -> None:
        """Add an error message to the results log."""
        results_log = self.query_one("#results_log", TextLog)
        error_text = Text(f"❌ {message}", style="bold red")
        results_log.write(error_text)
    
    def _add_warning_message(self, message: str) -> None:
        """Add a warning message to the results log."""
        results_log = self.query_one("#results_log", TextLog)
        warning_text = Text(f"⚠️ {message}", style="bold yellow")
        results_log.write(warning_text)
    
    # Action handlers for key bindings
    def action_quit(self) -> None:
        """Quit the application."""
        self.app.exit()
    
    def action_new_analysis(self) -> None:
        """Start a new analysis."""
        self._clear_results()
        self.selected_files.clear()
        self._update_selected_files_display()
        self._update_status("Ready for new analysis")
    
    def action_open_file(self) -> None:
        """Focus on file selection."""
        file_tree = self.query_one("#file_tree", DirectoryTree)
        file_tree.focus()
        self._update_status("Select files from the directory tree")
    
    def action_run_analysis(self) -> None:
        """Run analysis."""
        self._run_analysis()
    
    def action_save_results(self) -> None:
        """Save results."""
        self._save_results()
    
    def action_clear_results(self) -> None:
        """Clear results."""
        self._clear_results()
    
    def action_show_help(self) -> None:
        """Show help information."""
        help_text = """🔧 Analysis Commands:
• Ctrl+N - New analysis
• Ctrl+O - Focus file selection
• Ctrl+R - Run analysis
• Ctrl+S - Save results
• Ctrl+L - Clear results

⌨️ Navigation:
• F1 - Show this help
• F2 - Toggle file panel
• F3 - Toggle config panel
• Tab/Shift+Tab - Switch tabs
• Esc - Focus file tree

📋 Analysis Types:
• **Review** - Comprehensive code review
• **Explain** - Code explanation and walkthrough
• **Debug** - Help debug issues and errors
• **Optimize** - Performance and code optimization

💡 Tips:
• Select multiple files for batch analysis
• Configure analysis options in the right panel
• Use the table view for structured results
• Click table rows to see detailed information
• Results are displayed in multiple formats for easy review"""
        
        results_log = self.query_one("#results_log", TextLog)
        help_panel = Panel(
            help_text,
            title="📖 Analysis Help",
            border_style="yellow"
        )
        results_log.write(help_panel)
        results_log.write("")
    
    def action_toggle_file_panel(self) -> None:
        """Toggle file panel visibility."""
        file_panel = self.query_one("#file_panel")
        if file_panel.styles.display == "none":
            file_panel.styles.display = "block"
            self._update_status("File panel shown")
        else:
            file_panel.styles.display = "none"
            self._update_status("File panel hidden")
    
    def action_toggle_config_panel(self) -> None:
        """Toggle configuration panel visibility."""
        config_panel = self.query_one("#config_panel")
        if config_panel.styles.display == "none":
            config_panel.styles.display = "block"
            self._update_status("Configuration panel shown")
        else:
            config_panel.styles.display = "none"
            self._update_status("Configuration panel hidden")
    
    def action_focus_files(self) -> None:
        """Focus the file tree."""
        file_tree = self.query_one("#file_tree", DirectoryTree)
        file_tree.focus()
    
    def action_next_tab(self) -> None:
        """Switch to next tab."""
        tabs = self.query_one("#analysis_tabs", TabbedContent)
        tabs.action_next_tab()
    
    def action_prev_tab(self) -> None:
        """Switch to previous tab."""
        tabs = self.query_one("#analysis_tabs", TabbedContent)
        tabs.action_previous_tab()


# Fallback for when Textual is not available
if not TEXTUAL_AVAILABLE:
    class AnalyzeScreen:
        """Fallback AnalyzeScreen 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"
            )