"""VM management screen for deleting VMs/templates."""

from __future__ import annotations

from textual import work
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.screen import Screen
from textual.widgets import (
    Button,
    Footer,
    Header,
    Label,
    RichLog,
    SelectionList,
    Static,
)
from textual.widgets.selection_list import Selection

from tui.widgets.dialogs import ConfirmDialog


class VMManageScreen(Screen):
    """Screen for managing (deleting) VMs and templates."""

    BINDINGS = [
        Binding("escape", "back", "Back", show=True),
        Binding("d", "delete", "Delete Selected", show=True),
        Binding("r", "refresh", "Refresh", show=True),
    ]

    def __init__(self) -> None:
        super().__init__()
        self.vms: list[dict] = []

    def compose(self) -> ComposeResult:
        yield Header()
        with Vertical(classes="wizard-container"):
            yield Static("Manage VMs and Templates", classes="wizard-title")
            yield Static(
                "Select VMs/templates to delete (Space to toggle):",
                classes="wizard-step",
            )
            yield Vertical(id="vm-list-container", classes="wizard-content")
            with Horizontal(classes="wizard-nav"):
                yield Button("Delete Selected", id="delete", variant="error")
                yield Button("Refresh", id="refresh")
                yield Button("Back", id="back")
        yield Footer()

    def on_mount(self) -> None:
        self._load_vms()

    @work(exclusive=True)
    async def _load_vms(self) -> None:
        """Load all VMs from Proxmox."""
        self.vms = await self.app.proxmox.get_all_vms()
        self.app.call_later(self._display_vms)

    def _display_vms(self) -> None:
        """Display VM list."""
        container = self.query_one("#vm-list-container")
        container.remove_children()

        if not self.vms:
            container.mount(
                Static(
                    "[yellow]No VMs found.[/yellow]",
                    markup=True,
                )
            )
            return

        selections = []
        for vm in sorted(self.vms, key=lambda x: x.get("vmid", 0)):
            vmid = vm.get("vmid", 0)
            name = vm.get("name", "unknown")
            status = vm.get("status", "unknown")
            is_template = vm.get("template") == 1

            vm_type = "Template" if is_template else "VM"
            status_color = "green" if status == "running" else "red"

            label = f"{vmid}: {name} [{vm_type}] ({status})"
            selections.append(Selection(label, str(vmid), False))

        container.mount(SelectionList(*selections, id="vm-selection"))
        container.mount(
            Static(
                "\n[yellow]Warning:[/yellow] Deleting VMs/templates is permanent!",
                markup=True,
            )
        )

        # Focus the selection list after mount completes
        self.set_timer(0.1, self._focus_content)

    def _focus_content(self) -> None:
        """Focus the selection list."""
        try:
            self.query_one("#vm-selection", SelectionList).focus()
        except Exception:
            pass

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses."""
        if event.button.id == "delete":
            self.action_delete()
        elif event.button.id == "refresh":
            self.action_refresh()
        elif event.button.id == "back":
            self.action_back()

    def action_delete(self) -> None:
        """Delete selected VMs."""
        try:
            selection_list = self.query_one("#vm-selection", SelectionList)
        except Exception:
            self.notify("No VMs loaded", severity="warning")
            return

        selected = list(selection_list.selected)
        if not selected:
            self.notify("No VMs selected", severity="warning")
            return

        # Get VM names for confirmation
        vm_names = []
        for vmid_str in selected:
            vmid = int(vmid_str)
            for vm in self.vms:
                if vm.get("vmid") == vmid:
                    name = vm.get("name", "unknown")
                    vm_names.append(f"  - {vmid}: {name}")
                    break

        message = (
            f"Are you sure you want to delete {len(selected)} VM(s)?\n\n"
            + "\n".join(vm_names)
            + "\n\nThis action cannot be undone!"
        )

        async def handle_confirm(confirmed: bool) -> None:
            if confirmed:
                self.app.push_screen(
                    DeleteProgressScreen([int(v) for v in selected], self.vms)
                )

        self.app.push_screen(
            ConfirmDialog(
                "Confirm Deletion",
                message,
                yes_label="Delete",
                no_label="Cancel",
            ),
            handle_confirm,
        )

    def action_refresh(self) -> None:
        """Refresh VM list."""
        self._load_vms()

    def action_back(self) -> None:
        """Return to main menu."""
        self.app.pop_screen()


class DeleteProgressScreen(Screen):
    """Screen showing deletion progress."""

    BINDINGS = [
        Binding("escape", "back", "Back (when complete)", show=True),
    ]

    def __init__(self, vmids: list[int], vms: list[dict]) -> None:
        super().__init__()
        self.vmids = vmids
        self.vms = vms
        self.delete_complete = False

    def compose(self) -> ComposeResult:
        yield Header()
        with Vertical(classes="progress-container"):
            yield Static(f"Deleting {len(self.vmids)} VM(s)...", classes="progress-title")
            yield RichLog(id="output", classes="progress-output", highlight=True)
            with Horizontal(classes="wizard-nav"):
                yield Button("Close", id="close", disabled=True)
        yield Footer()

    def on_mount(self) -> None:
        self.run_delete()

    @work(exclusive=True, exit_on_error=False)
    async def run_delete(self) -> None:
        """Delete the selected VMs."""
        output = self.query_one("#output", RichLog)
        success_count = 0
        fail_count = 0

        for vmid in self.vmids:
            # Find VM name
            name = "unknown"
            for vm in self.vms:
                if vm.get("vmid") == vmid:
                    name = vm.get("name", "unknown")
                    break

            self.app.call_later(output.write, f"Deleting VM {vmid} ({name})...")

            success = await self.app.proxmox.destroy_vm(vmid)

            if success:
                self.app.call_later(
                    output.write, f"[green]  Successfully deleted {vmid}[/green]"
                )
                success_count += 1
            else:
                self.app.call_later(
                    output.write, f"[red]  Failed to delete {vmid}[/red]"
                )
                fail_count += 1

        self.delete_complete = True

        self.app.call_later(output.write, "")
        self.app.call_later(
            output.write,
            f"Deletion complete: {success_count} succeeded, {fail_count} failed",
        )

        self.app.call_later(self._enable_close)

    def _enable_close(self) -> None:
        """Enable the close button."""
        self.query_one("#close", Button).disabled = False

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "close":
            # Pop both progress and manage screens, return to main
            self.app.pop_screen()
            self.app.pop_screen()

    def action_back(self) -> None:
        if self.delete_complete:
            self.app.pop_screen()
            self.app.pop_screen()
