"""Slop Trough widget for .calf file management."""

from collections.abc import Callable
from pathlib import Path

from textual.app import ComposeResult
from textual.containers import Vertical
from textual.reactive import reactive
from textual.widgets import Button, Label, OptionList, Static
from textual.widgets.option_list import Option


class SlopTrough(Vertical):
    """Panel for managing .calf directive files.

    Lists available .calf files and shows a preview of the selected file.
    "Perform Calf Raises" initiates the interrogation flow.

    Interface for sibling integration:
        refresh_files() - Refresh the file list
        on_file_selected: Callable[[Path], None] - File selection callback
        on_calf_raises: Callable[[], None] - Callback for interrogation flow
    """

    DEFAULT_CSS = """
    SlopTrough {
        height: 100%;
        padding: 0 1;
    }

    SlopTrough Label {
        margin-bottom: 0;
    }

    SlopTrough OptionList {
        height: 1fr;
        min-height: 3;
        margin-bottom: 1;
        border: solid $panel;
    }

    SlopTrough .preview-container {
        display: none;
    }

    SlopTrough .preview-label {
        display: none;
    }

    SlopTrough #calf-raises-button {
        margin-top: 0;
        width: 100%;
        dock: bottom;
    }
    """

    # Directory to scan for .calf files
    directory: reactive[Path | None] = reactive(None)

    # Currently selected file
    selected_file: reactive[Path | None] = reactive(None)

    # Callbacks
    on_file_selected: Callable[[Path], None] | None = None
    on_calf_raises: Callable[[], None] | None = None

    def compose(self) -> ComposeResult:
        """Compose the file list and preview."""
        yield Label(".calf files:")
        yield OptionList(id="calf-list")

        yield Label("Preview:", classes="preview-label")
        yield Static("Select a file to preview", id="preview-content", classes="preview-container")

        yield Button("Perform Calf Raises", id="calf-raises-button", variant="success")

    def on_mount(self) -> None:
        """Initialize with current directory if set."""
        if self.directory:
            self.refresh_files()

    def watch_directory(self, value: Path | None) -> None:
        """Refresh file list when directory changes."""
        if value is not None and self.is_mounted:
            self.refresh_files()

    def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
        """Handle file selection."""
        if event.option.id:
            path = Path(event.option.id)
            self.selected_file = path
            self._update_preview(path)

            if self.on_file_selected is not None:
                self.on_file_selected(path)

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "calf-raises-button" and self.on_calf_raises is not None:
            self.on_calf_raises()

    def refresh_files(self) -> None:
        """Refresh the file list from the directory."""
        option_list = self.query_one("#calf-list", OptionList)
        option_list.clear_options()

        if self.directory is None:
            return

        if not self.directory.exists():
            return

        calf_files = sorted(self.directory.glob("*.calf"))

        for calf_file in calf_files:
            option_list.add_option(Option(calf_file.name, id=str(calf_file)))

    def _update_preview(self, path: Path) -> None:
        """Update the preview pane with file contents."""
        preview = self.query_one("#preview-content", Static)

        if not path.exists():
            preview.update("[red]File not found[/]")
            return

        try:
            content = path.read_text()
            # Truncate for preview
            if len(content) > 500:
                content = content[:500] + "\n[dim]...[/]"
            preview.update(content)
        except Exception as e:
            preview.update(f"[red]Error reading file: {e}[/]")

    def get_files(self) -> list[Path]:
        """Get list of .calf files in the directory.

        Returns:
            List of paths to .calf files
        """
        if self.directory is None or not self.directory.exists():
            return []
        return sorted(self.directory.glob("*.calf"))
