"""
Cloudflare Tab for credential and DNS management
"""

from textual.widgets import Static, Button, DataTable, Label, Input
from textual.containers import Horizontal, Vertical
from textual.app import ComposeResult
from textual.screen import ModalScreen
from ..core.cloudflare import CloudflareManager
from ..core.config import Config


class AddTokenDialog(ModalScreen):
    """Dialog for adding a new Cloudflare API token"""

    CSS = """
    #token-dialog {
        align: center middle;
        border: thick cyan;
        padding: 2;
        background: $surface;
        width: 70;
    }

    #token-dialog-title {
        text-align: center;
        text-style: bold;
        margin-bottom: 1;
    }

    #token-dialog Label {
        margin-top: 1;
    }

    #token-dialog-buttons {
        align: center middle;
        margin-top: 2;
    }

    #token-dialog-buttons Button {
        min-width: 12;
        margin: 0 2;
    }

    #token-scope-buttons {
        margin-top: 1;
    }

    #token-scope-buttons Button {
        min-width: 20;
        margin: 0 1;
    }
    """

    def __init__(self):
        super().__init__()
        self.save_as_system = False

    def compose(self) -> ComposeResult:
        yield Vertical(
            Label("Add Cloudflare API Token", id="token-dialog-title"),
            Label("Name (e.g., 'Production', 'Personal'):", id="token-name-label"),
            Input(placeholder="Token name", id="token-name-input"),
            Label("API Token:", id="token-value-label"),
            Input(placeholder="Paste your API token here", id="token-value-input", password=True),
            Label("[dim]Get token from: https://dash.cloudflare.com/profile/api-tokens[/]", id="token-help"),
            Label("Save to:", id="token-scope-label"),
            Horizontal(
                Button("User (personal)", id="token-scope-user", variant="primary"),
                Button("System (shared)", id="token-scope-system", variant="default"),
                id="token-scope-buttons"
            ),
            Horizontal(
                Button("Add", id="token-add-btn", variant="success"),
                Button("Cancel", id="token-cancel-btn", variant="default"),
                id="token-dialog-buttons"
            ),
            id="token-dialog"
        )

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "token-scope-user":
            self.save_as_system = False
            self.query_one("#token-scope-user", Button).variant = "primary"
            self.query_one("#token-scope-system", Button).variant = "default"
        elif event.button.id == "token-scope-system":
            self.save_as_system = True
            self.query_one("#token-scope-user", Button).variant = "default"
            self.query_one("#token-scope-system", Button).variant = "primary"
        elif event.button.id == "token-add-btn":
            name = self.query_one("#token-name-input", Input).value.strip()
            token = self.query_one("#token-value-input", Input).value.strip()

            if not name or not token:
                self.app.notify("Name and token are required", severity="error")
                return

            scope = "system" if self.save_as_system else "user"
            if Config.add_cloudflare_token(name, token, system=self.save_as_system):
                self.app.notify(f"Token '{name}' added to {scope} config", severity="information")
                self.dismiss(True)
            else:
                self.app.notify(f"Failed to save token to {scope} config", severity="error")
        else:
            self.dismiss(False)


class CloudflareTab(Static):
    """Tab for Cloudflare credential and DNS management"""

    # State tracking
    selected_credential: str | None = None
    credential_data: dict = {}  # {name: {token, created_at, zones}}

    def compose(self) -> ComposeResult:
        yield Label("Cloudflare Credential Management", id="cf-title")
        yield Label("Press **R** to refresh", id="cf-help")

        # Credentials section
        yield Label("API Tokens (select row to manage)", id="cf-creds-title")
        yield DataTable(id="cf-creds-table", cursor_type="row")
        yield Label("Selected: [dim]None[/]", id="cf-selected-label")
        yield Horizontal(
            Button("Add Token", id="cf-add-token", variant="success"),
            Button("Test Token", id="cf-test-token", variant="primary", disabled=True),
            Button("Delete Token", id="cf-delete-token", variant="error", disabled=True),
            id="cf-cred-buttons"
        )

        yield Label("", id="cf-spacer")

        # Zones section
        yield Label("Domains/Zones (from all tokens)", id="cf-zones-title")
        yield DataTable(id="cf-zones-table")

    def on_mount(self) -> None:
        """Initialize tables when tab is mounted"""
        self.refresh_credentials()
        self.refresh_zones()

    def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
        """Handle row selection in the credentials table"""
        if event.data_table.id != "cf-creds-table":
            return

        self.selected_credential = str(event.row_key.value) if event.row_key else None
        self.update_selected_label()
        self.update_button_states()

    def update_selected_label(self) -> None:
        """Update the selected credential label"""
        try:
            label = self.query_one("#cf-selected-label", Label)
            if self.selected_credential:
                data = self.credential_data.get(self.selected_credential, {})
                zones_count = data.get("zones_count", "?")
                source = data.get("source", "user")
                source_str = "[cyan](user)[/]" if source == "user" else "[yellow](system)[/]"
                label.update(f"Selected: [bold]{self.selected_credential}[/] {source_str} - {zones_count} zone(s)")
            else:
                label.update("Selected: [dim]None[/]")
        except Exception:
            pass

    def update_button_states(self) -> None:
        """Enable/disable buttons based on selection"""
        try:
            test_btn = self.query_one("#cf-test-token", Button)
            delete_btn = self.query_one("#cf-delete-token", Button)

            if self.selected_credential:
                test_btn.disabled = False
                delete_btn.disabled = False
            else:
                test_btn.disabled = True
                delete_btn.disabled = True
        except Exception:
            pass

    def refresh_credentials(self) -> None:
        """Refresh credentials table"""
        try:
            table = self.query_one("#cf-creds-table", DataTable)
            table.clear(columns=True)
            table.add_column("Name", width=18)
            table.add_column("Source", width=10)
            table.add_column("Created", width=20)
            table.add_column("Status", width=12)
            table.add_column("Zones", width=8)

            tokens = Config.get_cloudflare_tokens()
            self.credential_data = {}

            for name, data in tokens.items():
                token = data.get("token", "")
                source = data.get("source", "user")
                created = data.get("created_at", "Unknown")
                if created and len(created) > 16:
                    created = created[:16]  # Trim to date + time

                # Format source display
                source_str = "[cyan]user[/]" if source == "user" else "[yellow]system[/]"

                # Test token and get zones count
                status = "[dim]?[/]"
                zones_count = 0

                if token:
                    manager = CloudflareManager(token_name=name)
                    result = manager.test_connection()
                    if result.get("success"):
                        status = "[green]Valid[/]"
                        zones = manager.list_zones()
                        zones_count = len(zones)
                    else:
                        status = "[red]Invalid[/]"

                self.credential_data[name] = {
                    "token": token,
                    "source": source,
                    "created_at": created,
                    "zones_count": zones_count
                }

                table.add_row(name, source_str, created, status, str(zones_count), key=name)

            self.update_button_states()
        except Exception as e:
            self.notify(f"Error refreshing credentials: {e}", severity="error")

    def refresh_zones(self) -> None:
        """Refresh zones table from all credentials"""
        try:
            table = self.query_one("#cf-zones-table", DataTable)
            table.clear(columns=True)
            table.add_column("Domain", width=30)
            table.add_column("Credential", width=20)
            table.add_column("Status", width=15)
            table.add_column("Zone ID", width=35)

            zones = CloudflareManager.get_all_zones_from_all_credentials()

            for zone in zones:
                status = zone.get("status", "unknown")
                if status == "active":
                    status_str = "[green]Active[/]"
                else:
                    status_str = f"[yellow]{status}[/]"

                table.add_row(
                    zone.get("zone_name", ""),
                    zone.get("credential_name", ""),
                    status_str,
                    zone.get("zone_id", "")[:20] + "..."
                )

        except Exception as e:
            self.notify(f"Error refreshing zones: {e}", severity="error")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle button presses"""
        if event.button.id == "cf-add-token":
            self.app.push_screen(AddTokenDialog(), self.on_token_added)
        elif event.button.id == "cf-test-token":
            self.test_selected_token()
        elif event.button.id == "cf-delete-token":
            self.delete_selected_token()

    def on_token_added(self, result: bool) -> None:
        """Called when token dialog is dismissed"""
        if result:
            self.refresh_credentials()
            self.refresh_zones()

    def test_selected_token(self) -> None:
        """Test the selected token"""
        if not self.selected_credential:
            return

        credential_name = self.selected_credential
        self.notify(f"Testing token '{credential_name}'...", severity="information")

        def do_test():
            manager = CloudflareManager(token_name=credential_name)
            result = manager.test_connection()
            zones = manager.list_zones() if result.get("success") else []

            # Call back to main thread with results
            if result.get("success"):
                self.app.call_from_thread(
                    self.notify, f"Token valid! Access to {len(zones)} zone(s)", severity="information"
                )
            else:
                error = result.get("error", "Unknown error")
                self.app.call_from_thread(
                    self.notify, f"Token invalid: {error}", severity="error"
                )

        self.app.run_worker(do_test, thread=True)

    def delete_selected_token(self) -> None:
        """Delete the selected token"""
        if not self.selected_credential:
            return

        name = self.selected_credential

        if Config.remove_cloudflare_token(name):
            self.notify(f"Token '{name}' deleted", severity="information")
            self.selected_credential = None
            self.refresh_credentials()
            self.refresh_zones()
        else:
            self.notify(f"Failed to delete token", severity="error")
