"""
Edit screen for the MiniMax TUI interface.

Provides an interactive file editing interface with file selection, edit type selection,
side-by-side code display, diff visualization, and real-time preview capabilities.
"""

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 FileSelected(Message):
    """Message for when a file is selected."""
    
    def __init__(self, file_path: str) -> None:
        self.file_path = file_path
        super().__init__()


class EditTypeChanged(Message):
    """Message for when edit type is changed."""
    
    def __init__(self, edit_type: str) -> None:
        self.edit_type = edit_type
        super().__init__()


class PreviewGenerated(Message):
    """Message for when preview is generated."""
    
    def __init__(self, original_code: str, modified_code: str, language: str) -> None:
        self.original_code = original_code
        self.modified_code = modified_code
        self.language = language
        super().__init__()


class EditScreen(Screen):
    """Interactive edit screen for MiniMax TUI."""
    
    BINDINGS = [
        Binding("ctrl+c", "quit", "Quit"),
        Binding("ctrl+o", "open_file", "Open File"),
        Binding("ctrl+s", "save_changes", "Save Changes"),
        Binding("ctrl+p", "generate_preview", "Generate Preview"),
        Binding("ctrl+r", "reset_changes", "Reset"),
        Binding("ctrl+b", "toggle_backup", "Toggle Backup"),
        Binding("f1", "show_help", "Help"),
        Binding("f2", "toggle_diff_view", "Toggle Diff View"),
        Binding("f3", "toggle_side_by_side", "Toggle Side-by-Side"),
        Binding("escape", "focus_instruction", "Focus Instruction"),
    ]
    
    CSS = """
    EditScreen {
        layout: grid;
        grid-size: 4 3;
        grid-columns: 250px 1fr 1fr 250px;
        grid-rows: auto 1fr auto;
    }
    
    #header_container {
        column-span: 4;
        row-span: 1;
        height: auto;
        background: $surface;
        border-bottom: solid $primary;
    }
    
    #file_panel {
        column-span: 1;
        row-span: 1;
        background: $surface;
        border-right: solid $primary;
    }
    
    #original_panel {
        column-span: 1;
        row-span: 1;
        background: $background;
        border-right: solid $border;
    }
    
    #modified_panel {
        column-span: 1;
        row-span: 1;
        background: $background;
        border-right: solid $border;
    }
    
    #control_panel {
        column-span: 1;
        row-span: 1;
        background: $surface;
    }
    
    #footer_container {
        column-span: 4;
        row-span: 1;
        height: auto;
        background: $surface;
        border-top: solid $primary;
    }
    
    #file_tree {
        height: 1fr;
        border: solid $accent;
    }
    
    #edit_options {
        height: auto;
        margin: 1 0;
    }
    
    #instruction_input {
        height: 6;
        border: solid $primary;
        margin: 1 0;
    }
    
    #target_input {
        height: 3;
        border: solid $accent;
        margin: 1 0;
    }
    
    #original_code {
        height: 1fr;
        border: solid $success;
        scrollbar-gutter: stable;
    }
    
    #modified_code {
        height: 1fr;
        border: solid $warning;
        scrollbar-gutter: stable;
    }
    
    #diff_table {
        height: 1fr;
        border: solid $info;
        display: none;
    }
    
    #progress_container {
        height: auto;
        margin: 1 0;
    }
    
    #progress_bar {
        display: none;
    }
    
    #action_buttons {
        height: auto;
        layout: horizontal;
        margin: 1 0;
    }
    
    #preview_button {
        width: 1fr;
        margin-right: 1;
    }
    
    #apply_button {
        width: 1fr;
        margin-right: 1;
    }
    
    #reset_button {
        width: 1fr;
    }
    
    #options_container {
        height: auto;
        margin: 1 0;
    }
    
    #backup_checkbox {
        margin: 1 0;
    }
    
    #style_select {
        margin: 1 0;
    }
    
    .panel-title {
        background: $primary;
        color: $text-inverse;
        padding: 0 1;
        text-align: center;
        text-style: bold;
    }
    
    .status-success {
        color: $success;
        text-style: bold;
    }
    
    .status-error {
        color: $error;
        text-style: bold;
    }
    
    .status-warning {
        color: $warning;
        text-style: bold;
    }
    
    .status-info {
        color: $info;
        text-style: bold;
    }
    
    .diff-added {
        background: $success 20%;
        color: $success;
    }
    
    .diff-removed {
        background: $error 20%;
        color: $error;
    }
    
    .diff-context {
        background: $surface;
        color: $text-muted;
    }
    """
    
    def __init__(self, client=None, config=None, edit_commands=None, **kwargs):
        super().__init__(**kwargs)
        self.client = client
        self.config = config
        self.edit_commands = edit_commands
        
        # State management
        self.selected_file: Optional[str] = None
        self.edit_type: str = "modify"
        self.original_code: str = ""
        self.modified_code: str = ""
        self.language: str = "text"
        self.has_changes: bool = False
        self.backup_enabled: bool = True
        self.diff_view_mode: str = "side_by_side"  # "side_by_side", "unified", "table"
        
        # Reactive state
        self.is_processing = reactive(False)
        self.current_operation = reactive("")
        
    def compose(self) -> ComposeResult:
        """Compose the edit screen layout."""
        # Header with current file and status
        with Container(id="header_container"):
            yield Static("📝 File Editor", classes="panel-title")
            yield Label("No file selected", id="file_status")
            yield Label("", id="operation_status")
        
        # File selection panel
        with Container(id="file_panel"):
            yield Static("📁 File Browser", classes="panel-title")
            yield DirectoryTree("./", id="file_tree")
            yield Static("", id="file_info")
        
        # Original code panel
        with Container(id="original_panel"):
            yield Static("📄 Original Code", classes="panel-title")
            yield TextLog(
                id="original_code",
                highlight=True,
                markup=True,
                wrap=False,
                auto_scroll=False
            )
        
        # Modified code panel
        with Container(id="modified_panel"):
            yield Static("✏️ Modified Code", classes="panel-title")
            yield TextLog(
                id="modified_code",
                highlight=True,
                markup=True,
                wrap=False,
                auto_scroll=False
            )
            yield DataTable(id="diff_table", show_header=True, zebra_stripes=True)
        
        # Control panel
        with Container(id="control_panel"):
            yield Static("⚙️ Edit Controls", classes="panel-title")
            
            # Edit type selection
            with Container(id="edit_options"):
                yield Label("Edit Type:")
                yield RadioSet(
                    RadioButton("Modify", value=True, id="modify_radio"),
                    RadioButton("Refactor", id="refactor_radio"),
                    RadioButton("Format", id="format_radio"),
                    id="edit_type_radio"
                )
            
            # Instruction input
            yield Label("Instructions:")
            yield Input(
                placeholder="Enter modification instructions...",
                id="instruction_input"
            )
            
            # Target input (for refactoring)
            yield Label("Target (for refactoring):")
            yield Input(
                placeholder="Function/variable name to refactor...",
                id="target_input"
            )
            
            # Options
            with Container(id="options_container"):
                yield Checkbox("Create backup", value=True, id="backup_checkbox")
                yield Label("Style (for formatting):")
                yield Select(
                    [
                        ("Standard", "standard"),
                        ("PEP8", "pep8"),
                        ("Google", "google"),
                        ("Black", "black"),
                        ("Prettier", "prettier")
                    ],
                    value="standard",
                    id="style_select"
                )
            
            # Progress indicator
            with Container(id="progress_container"):
                yield ProgressBar(
                    id="progress_bar",
                    show_eta=False,
                    show_percentage=False
                )
                yield Label("", id="progress_label")
            
            # Action buttons
            with Horizontal(id="action_buttons"):
                yield Button("Preview", id="preview_button", variant="primary")
                yield Button("Apply", id="apply_button", variant="success")
                yield Button("Reset", id="reset_button", variant="warning")
        
        # Footer with shortcuts and status
        with Container(id="footer_container"):
            yield Label("Ctrl+O: Open | Ctrl+P: Preview | Ctrl+S: Save | F2: Toggle Diff | F3: Side-by-Side", id="shortcuts")
    
    def on_mount(self) -> None:
        """Initialize the screen when mounted."""
        self._update_file_status()
        self._update_operation_status("Ready")
        self.query_one("#instruction_input").focus()
        
        # Initialize diff table columns
        diff_table = self.query_one("#diff_table", DataTable)
        diff_table.add_columns("Line", "Type", "Original", "Modified")
    
    def on_directory_tree_file_selected(self, event: DirectoryTree.FileSelected) -> None:
        """Handle file selection from directory tree."""
        self.selected_file = str(event.path)
        self._load_file()
    
    def on_radio_set_changed(self, event: RadioSet.Changed) -> None:
        """Handle edit type radio button changes."""
        if event.radio_set.id == "edit_type_radio":
            if event.pressed.id == "modify_radio":
                self.edit_type = "modify"
            elif event.pressed.id == "refactor_radio":
                self.edit_type = "refactor"
            elif event.pressed.id == "format_radio":
                self.edit_type = "format"
            
            self._update_ui_for_edit_type()
    
    def on_checkbox_changed(self, event: Checkbox.Changed) -> None:
        """Handle checkbox changes."""
        if event.checkbox.id == "backup_checkbox":
            self.backup_enabled = event.value
    
    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "preview_button":
            self._generate_preview()
        elif event.button.id == "apply_button":
            self._apply_changes()
        elif event.button.id == "reset_button":
            self._reset_changes()
    
    def _load_file(self) -> None:
        """Load the selected file."""
        if not self.selected_file or not os.path.exists(self.selected_file):
            self._update_operation_status("File not found", "error")
            return
        
        try:
            with open(self.selected_file, 'r', encoding='utf-8') as f:
                self.original_code = f.read()
            
            self.language = self._detect_language(self.selected_file)
            self.modified_code = ""
            self.has_changes = False
            
            # Display original code
            self._display_original_code()
            self._clear_modified_code()
            self._update_file_status()
            self._update_file_info()
            self._update_operation_status("File loaded successfully", "success")
            
        except Exception as e:
            self._update_operation_status(f"Error loading file: {str(e)}", "error")
    
    def _display_original_code(self) -> None:
        """Display the original code with syntax highlighting."""
        original_log = self.query_one("#original_code", TextLog)
        original_log.clear()
        
        if self.original_code:
            try:
                syntax = Syntax(
                    self.original_code,
                    self.language,
                    theme="monokai",
                    line_numbers=True,
                    word_wrap=False
                )
                original_log.write(syntax)
            except Exception:
                # Fallback to plain text
                original_log.write(self.original_code)
    
    def _display_modified_code(self) -> None:
        """Display the modified code with syntax highlighting."""
        modified_log = self.query_one("#modified_code", TextLog)
        modified_log.clear()
        
        if self.modified_code:
            try:
                syntax = Syntax(
                    self.modified_code,
                    self.language,
                    theme="monokai",
                    line_numbers=True,
                    word_wrap=False
                )
                modified_log.write(syntax)
            except Exception:
                # Fallback to plain text
                modified_log.write(self.modified_code)
    
    def _clear_modified_code(self) -> None:
        """Clear the modified code display."""
        modified_log = self.query_one("#modified_code", TextLog)
        modified_log.clear()
        modified_log.write(Text("No modifications yet", style="dim"))
    
    def _update_file_status(self) -> None:
        """Update the file status display."""
        file_status = self.query_one("#file_status", Label)
        
        if self.selected_file:
            file_name = Path(self.selected_file).name
            status_text = f"📄 {file_name}"
            if self.has_changes:
                status_text += " (modified)"
            file_status.update(status_text)
        else:
            file_status.update("No file selected")
    
    def _update_operation_status(self, message: str, level: str = "info") -> None:
        """Update the operation status display."""
        operation_status = self.query_one("#operation_status", Label)
        
        if level == "success":
            operation_status.update(Text(f"✅ {message}", style="green"))
        elif level == "error":
            operation_status.update(Text(f"❌ {message}", style="red"))
        elif level == "warning":
            operation_status.update(Text(f"⚠️ {message}", style="yellow"))
        else:
            operation_status.update(Text(f"ℹ️ {message}", style="cyan"))
    
    def _update_file_info(self) -> None:
        """Update file information display."""
        file_info = self.query_one("#file_info", Static)
        
        if self.selected_file and os.path.exists(self.selected_file):
            stat = os.stat(self.selected_file)
            size = stat.st_size
            lines = len(self.original_code.splitlines()) if self.original_code else 0
            
            info_text = f"""📊 File Info:
• Size: {self._format_size(size)}
• Lines: {lines:,}
• Language: {self.language}
• Encoding: UTF-8"""
            
            file_info.update(info_text)
        else:
            file_info.update("")
    
    def _update_ui_for_edit_type(self) -> None:
        """Update UI elements based on selected edit type."""
        instruction_input = self.query_one("#instruction_input", Input)
        target_input = self.query_one("#target_input", Input)
        style_select = self.query_one("#style_select", Select)
        
        if self.edit_type == "modify":
            instruction_input.placeholder = "Enter modification instructions..."
            target_input.disabled = True
            style_select.disabled = True
        elif self.edit_type == "refactor":
            instruction_input.placeholder = "Enter refactoring instructions..."
            target_input.disabled = False
            style_select.disabled = True
        elif self.edit_type == "format":
            instruction_input.placeholder = "Optional formatting instructions..."
            target_input.disabled = True
            style_select.disabled = False
    
    @work(exclusive=True)
    async def _generate_preview(self) -> None:
        """Generate preview of changes."""
        if not self.selected_file or not self.original_code:
            self._update_operation_status("No file selected", "error")
            return
        
        instruction = self.query_one("#instruction_input", Input).value.strip()
        target = self.query_one("#target_input", Input).value.strip()
        style = self.query_one("#style_select", Select).value
        
        if self.edit_type in ["modify", "refactor"] and not instruction:
            self._update_operation_status("Please enter instructions", "warning")
            return
        
        try:
            self.is_processing = True
            self._show_progress(f"Generating {self.edit_type} preview...")
            
            # Create mock args object for edit commands
            class MockArgs:
                def __init__(self):
                    self.file = self.selected_file
                    self.instruction = instruction
                    self.target = target if target else None
                    self.type = self.edit_type if self.edit_type == "refactor" else None
                    self.files = [self.selected_file] if self.edit_type == "format" else None
                    self.style = style
                    self.preview = True
                    self.backup = self.backup_enabled
            
            args = MockArgs()
            
            # Call appropriate edit command
            if self.edit_commands:
                if self.edit_type == "modify":
                    success = await self._run_in_thread(self.edit_commands.modify, args)
                elif self.edit_type == "refactor":
                    success = await self._run_in_thread(self.edit_commands.refactor, args)
                elif self.edit_type == "format":
                    success = await self._run_in_thread(self.edit_commands.format_code, args)
                
                if success:
                    # For now, simulate getting the modified code
                    # In a real implementation, this would come from the edit commands
                    self.modified_code = await self._simulate_modification()
                    self.has_changes = True
                    
                    self.call_from_thread(self._display_modified_code)
                    self.call_from_thread(self._update_diff_display)
                    self.call_from_thread(self._update_file_status)
                    self.call_from_thread(self._update_operation_status, "Preview generated", "success")
                else:
                    self.call_from_thread(self._update_operation_status, "Failed to generate preview", "error")
            else:
                # Fallback simulation
                self.modified_code = await self._simulate_modification()
                self.has_changes = True
                
                self.call_from_thread(self._display_modified_code)
                self.call_from_thread(self._update_diff_display)
                self.call_from_thread(self._update_file_status)
                self.call_from_thread(self._update_operation_status, "Preview generated (simulated)", "success")
                
        except Exception as e:
            self.call_from_thread(self._update_operation_status, f"Error: {str(e)}", "error")
        finally:
            self.is_processing = False
            self.call_from_thread(self._hide_progress)
    
    async def _run_in_thread(self, func, *args):
        """Run a function in a thread."""
        import concurrent.futures
        
        loop = asyncio.get_event_loop()
        with concurrent.futures.ThreadPoolExecutor() as executor:
            return await loop.run_in_executor(executor, func, *args)
    
    async def _simulate_modification(self) -> str:
        """Simulate code modification for preview."""
        await asyncio.sleep(1)  # Simulate processing time
        
        instruction = self.query_one("#instruction_input", Input).value.strip()
        
        # Simple simulation based on edit type
        if self.edit_type == "modify":
            return f"# Modified based on: {instruction}\n{self.original_code}\n\n# End of modifications"
        elif self.edit_type == "refactor":
            return f"# Refactored code\n{self.original_code}\n\n# Refactoring complete"
        elif self.edit_type == "format":
            # Simple formatting simulation
            lines = self.original_code.split('\n')
            formatted_lines = [line.strip() for line in lines if line.strip()]
            return '\n'.join(formatted_lines)
        
        return self.original_code
    
    def _update_diff_display(self) -> None:
        """Update the diff display based on current view mode."""
        if self.diff_view_mode == "table":
            self._show_diff_table()
        else:
            self._hide_diff_table()
    
    def _show_diff_table(self) -> None:
        """Show differences in table format."""
        diff_table = self.query_one("#diff_table", DataTable)
        modified_log = self.query_one("#modified_code", TextLog)
        
        # Hide modified code log and show diff table
        modified_log.styles.display = "none"
        diff_table.styles.display = "block"
        
        # Clear existing rows
        diff_table.clear()
        
        if not self.original_code or not self.modified_code:
            return
        
        # Generate diff data
        diff_data = self._create_diff_data()
        
        # Add rows to table
        for row in diff_data:
            diff_table.add_row(
                row["line"],
                row["type"],
                row["original"][:50] + "..." if len(row["original"]) > 50 else row["original"],
                row["modified"][:50] + "..." if len(row["modified"]) > 50 else row["modified"]
            )
    
    def _hide_diff_table(self) -> None:
        """Hide diff table and show modified code."""
        diff_table = self.query_one("#diff_table", DataTable)
        modified_log = self.query_one("#modified_code", TextLog)
        
        # Show modified code log and hide diff table
        modified_log.styles.display = "block"
        diff_table.styles.display = "none"
    
    def _create_diff_data(self) -> List[Dict[str, str]]:
        """Create diff data for table display."""
        import difflib
        
        original_lines = self.original_code.splitlines()
        modified_lines = self.modified_code.splitlines()
        
        diff_data = []
        
        # Create unified diff
        diff = list(difflib.unified_diff(
            original_lines,
            modified_lines,
            lineterm='',
            n=3
        ))
        
        if not diff:
            return []
        
        line_num_orig = 0
        line_num_mod = 0
        
        for line in diff[2:]:  # Skip header lines
            if line.startswith('@@'):
                # Parse line numbers from hunk header
                import re
                match = re.match(r'@@ -(\d+),?\d* \+(\d+),?\d* @@', line)
                if match:
                    line_num_orig = int(match.group(1))
                    line_num_mod = int(match.group(2))
                continue
            
            line_content = line[1:] if line else ''
            
            if line.startswith('-'):
                diff_data.append({
                    "line": str(line_num_orig),
                    "type": "Removed",
                    "original": line_content,
                    "modified": ""
                })
                line_num_orig += 1
            elif line.startswith('+'):
                diff_data.append({
                    "line": str(line_num_mod),
                    "type": "Added",
                    "original": "",
                    "modified": line_content
                })
                line_num_mod += 1
            else:
                diff_data.append({
                    "line": f"{line_num_orig}/{line_num_mod}",
                    "type": "Context",
                    "original": line_content,
                    "modified": line_content
                })
                line_num_orig += 1
                line_num_mod += 1
        
        return diff_data
    
    def _apply_changes(self) -> None:
        """Apply the changes to the file."""
        if not self.selected_file or not self.has_changes:
            self._update_operation_status("No changes to apply", "warning")
            return
        
        if not self.modified_code:
            self._update_operation_status("No modified code available", "warning")
            return
        
        try:
            # Create backup if enabled
            if self.backup_enabled:
                backup_path = f"{self.selected_file}.backup"
                with open(backup_path, 'w', encoding='utf-8') as f:
                    f.write(self.original_code)
            
            # Write modified code
            with open(self.selected_file, 'w', encoding='utf-8') as f:
                f.write(self.modified_code)
            
            # Update state
            self.original_code = self.modified_code
            self.has_changes = False
            
            # Update displays
            self._display_original_code()
            self._clear_modified_code()
            self._update_file_status()
            
            status_msg = "Changes applied successfully"
            if self.backup_enabled:
                status_msg += " (backup created)"
            self._update_operation_status(status_msg, "success")
            
        except Exception as e:
            self._update_operation_status(f"Error applying changes: {str(e)}", "error")
    
    def _reset_changes(self) -> None:
        """Reset all changes and reload the original file."""
        self.modified_code = ""
        self.has_changes = False
        
        self._clear_modified_code()
        self._update_file_status()
        self._update_operation_status("Changes reset", "info")
        
        # Clear inputs
        self.query_one("#instruction_input", Input).value = ""
        self.query_one("#target_input", Input).value = ""
    
    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 _detect_language(self, file_path: str) -> str:
        """Detect programming language from file extension."""
        ext = Path(file_path).suffix.lower()
        
        language_map = {
            '.py': 'python',
            '.js': 'javascript',
            '.ts': 'typescript',
            '.jsx': 'jsx',
            '.tsx': 'tsx',
            '.java': 'java',
            '.cpp': 'cpp',
            '.c': 'c',
            '.h': 'c',
            '.hpp': 'cpp',
            '.cs': 'csharp',
            '.php': 'php',
            '.rb': 'ruby',
            '.go': 'go',
            '.rs': 'rust',
            '.swift': 'swift',
            '.kt': 'kotlin',
            '.scala': 'scala',
            '.sh': 'bash',
            '.bash': 'bash',
            '.zsh': 'zsh',
            '.fish': 'fish',
            '.ps1': 'powershell',
            '.html': 'html',
            '.css': 'css',
            '.scss': 'scss',
            '.sass': 'sass',
            '.less': 'less',
            '.xml': 'xml',
            '.json': 'json',
            '.yaml': 'yaml',
            '.yml': 'yaml',
            '.toml': 'toml',
            '.ini': 'ini',
            '.cfg': 'ini',
            '.conf': 'ini',
            '.md': 'markdown',
            '.txt': 'text',
            '.sql': 'sql',
            '.r': 'r',
            '.R': 'r',
            '.m': 'matlab',
            '.pl': 'perl',
            '.lua': 'lua',
            '.vim': 'vim',
            '.dockerfile': 'dockerfile',
        }
        
        return language_map.get(ext, 'text')
    
    def _format_size(self, size: int) -> str:
        """Format file size in human readable format."""
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size < 1024:
                return f"{size:.1f} {unit}"
            size /= 1024
        return f"{size:.1f} TB"
    
    # Action handlers for key bindings
    def action_quit(self) -> None:
        """Quit the application."""
        self.app.exit()
    
    def action_open_file(self) -> None:
        """Focus file tree for file selection."""
        self.query_one("#file_tree").focus()
    
    def action_save_changes(self) -> None:
        """Save changes to file."""
        self._apply_changes()
    
    def action_generate_preview(self) -> None:
        """Generate preview of changes."""
        self._generate_preview()
    
    def action_reset_changes(self) -> None:
        """Reset all changes."""
        self._reset_changes()
    
    def action_toggle_backup(self) -> None:
        """Toggle backup option."""
        backup_checkbox = self.query_one("#backup_checkbox", Checkbox)
        backup_checkbox.value = not backup_checkbox.value
        self.backup_enabled = backup_checkbox.value
    
    def action_show_help(self) -> None:
        """Show help information."""
        help_text = """🔧 Edit Screen Help:

📁 File Operations:
• Select files from the directory tree
• Use Ctrl+O to focus file browser
• File info shows size, lines, and language

✏️ Edit Types:
• Modify: Make changes based on instructions
• Refactor: Restructure code (extract, inline, rename)
• Format: Apply code formatting and style

🔍 Preview & Apply:
• Ctrl+P: Generate preview of changes
• Ctrl+S: Apply changes to file
• Ctrl+R: Reset all changes

👀 View Options:
• F2: Toggle diff view mode
• F3: Toggle side-by-side view
• View original and modified code simultaneously

⚙️ Options:
• Backup: Create .backup file before changes
• Style: Choose formatting style for code
• Target: Specify element for refactoring

⌨️ Keyboard Shortcuts:
• Ctrl+O: Open file browser
• Ctrl+P: Generate preview
• Ctrl+S: Save changes
• Ctrl+R: Reset changes
• Ctrl+B: Toggle backup
• F1: Show this help
• F2: Toggle diff view
• F3: Toggle side-by-side
• Esc: Focus instruction input
• Ctrl+C: Quit"""
        
        # Show help in a modal or notification
        self._update_operation_status("Help displayed - see documentation", "info")
    
    def action_toggle_diff_view(self) -> None:
        """Toggle between diff view modes."""
        if self.diff_view_mode == "side_by_side":
            self.diff_view_mode = "table"
        else:
            self.diff_view_mode = "side_by_side"
        
        self._update_diff_display()
        self._update_operation_status(f"Diff view: {self.diff_view_mode}", "info")
    
    def action_toggle_side_by_side(self) -> None:
        """Toggle side-by-side view."""
        # This could adjust the layout or panel visibility
        self._update_operation_status("Side-by-side view toggled", "info")
    
    def action_focus_instruction(self) -> None:
        """Focus the instruction input field."""
        self.query_one("#instruction_input").focus()


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