'''Modal helpers for opencos.tui, to select EDA commands, tools, additional args'''

import os

from textual.screen import ModalScreen
from textual.widgets import Input, Checkbox, Button, OptionList, Label
from textual.containers import Vertical, Horizontal
from textual.app import ComposeResult

DEFAULT = '( default / None )'

def get_tool_arg(tool: str) -> str:
    '''Returns the selected TOOL arg as --tool=TOOL, if empty or default returns emtpy str'''
    if tool and tool != DEFAULT:
        return f'--tool={tool}'
    return ''


class ToolPickerModal(ModalScreen[str]):
    '''Modal for picking a tool'''

    def __init__(self, file_path: str, tools: list[str], add_default: bool):
        super().__init__()
        self.file_path = file_path
        if add_default:
            self.tools = [DEFAULT] + tools
        else:
            self.tools = tools

    def compose(self) -> ComposeResult:
        with Vertical(id="modal-dialog"):
            yield Label(f"Open [cyan]{os.path.basename(self.file_path)}[/] with:")
            # Yield your pre-filtered list of tools
            yield OptionList(*self.tools, id="tool-list")

    def on_option_list_option_selected(
            self, event: OptionList.OptionSelected
    ) -> None:
        '''Handles selecting a tool from the list'''
        # self.dismiss() sends the result back to the callback in MainScreen
        self.dismiss(str(event.option.prompt))

    def on_key(self, event) -> None:
        '''Handles pressing escape to cancel'''
        if event.key == "escape":
            self.dismiss(None)


class ActionDetailsModal(ModalScreen[dict]):
    '''Modal for picking additional args, and 'waves' if this is 'sim' command'''

    def __init__(self, target_name: str, cmd: str, tool: str):
        super().__init__()
        self.target_name = target_name
        self.cmd = cmd
        self.tool = tool

    def compose(self) -> ComposeResult:
        with Vertical(id="modal-dialog"):
            yield Label(
                f"Finalizing [cyan]{self.cmd} {self.target_name}[/] with [green]{self.tool}[/]"
            )

            # Additional Args Input
            yield Label("Additional Args:")
            yield Input(placeholder="e.g., --verbose --seed 1234", id="extra-args")

            # Waves Checkbox
            if self.cmd == 'sim':
                yield Checkbox("Run with --waves?", value=False, id="waves-check")

            with Horizontal(id="modal-buttons"):
                yield Button("To CLI", variant="success", id="run-btn")
                yield Button("Cancel", variant="error", id="cancel-btn")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        '''Handles a 'To CLI' button'''
        if event.button.id == "run-btn":
            # Collect and return the data
            ret_dict = {
                "args": self.query_one("#extra-args", Input).value
            }
            if self.cmd == 'sim':
                ret_dict['waves'] = self.query_one("#waves-check", Checkbox).value
            self.dismiss(ret_dict)

        else:
            self.dismiss(None)
