
from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import Vertical, Horizontal, VerticalScroll
from textual.widgets import Static, Button, Switch, Input, ListItem, ListView
from textual.message import Message
from textual.binding import Binding

from plugins import get_plugin_loader, PluginMeta

class PluginsTab(Vertical):

    DEFAULT_CSS = """
    PluginsTab {
        width: 100%;
        height: 100%;
    }

    #plugins_scroll {
        width: 100%;
        height: 1fr;
    }

    #plugins_container {
        width: 100%;
        height: auto;
    }

    .plugin-row {
        width: 100%;
        height: 3;
        background: $surface;
        padding: 0 1;
        align-vertical: middle;
    }

    .plugin-row:hover {
        background: $surface-lighten-1;
    }

    .plugin-name {
        width: 1fr;
        height: auto;
        content-align: left middle;
    }

    .plugin-btn {
        width: 5;
        height: auto;
        min-height: 1;
        margin-right: 2;
    }

    .plugin-switch {
        width: auto;
        height: auto;
    }

    #plugins_footer {
        width: 100%;
        height: 3;
        dock: bottom;
        background: $surface;
        padding: 0 1;
        align-vertical: middle;
    }

    #plugins_footer Button {
        margin-right: 1;
    }
    """

    def __init__(self):
        super().__init__()
        self._filter = ""

    def compose(self) -> ComposeResult:
        with VerticalScroll(id="plugins_scroll"):
            with Vertical(id="plugins_container"):
                yield from self._build_plugin_list()

        with Horizontal(id="plugins_footer"):
            yield Button("Yenile", id="btn_refresh", variant="default")
            yield Button("Klasörü Aç", id="btn_open_folder", variant="default")

    def _build_plugin_list(self):
        loader = get_plugin_loader()
        plugins = loader.get_all_plugin_metas()

        if not plugins:
            yield Static("[dim]Plugin bulunamadı[/]")
            return

        for plugin_id, meta, enabled in sorted(plugins, key=lambda x: x[1].name.lower()):

            status_symbol = "[green]✓[/]" if enabled else "[red]✗[/]"
            display_name = f"{status_symbol}  {meta.name}"

            has_settings = False
            plugin = loader.get_plugin(plugin_id)
            if plugin and plugin.settings:
                has_settings = True
            else:
                plugin_class = loader._plugin_classes.get(plugin_id)
                if plugin_class:
                    try:
                        temp = plugin_class()
                        has_settings = bool(temp.settings)
                    except:
                        pass

            children = []
            children.append(Static(display_name, classes="plugin-name"))

            if has_settings:
                children.append(Button("⚙", id=f"cfg_{plugin_id}", classes="plugin-btn", variant="default"))

            children.append(Switch(value=enabled, id=f"sw_{plugin_id}", classes="plugin-switch"))

            yield Horizontal(*children, classes="plugin-row", id=f"row_{plugin_id}")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        btn_id = event.button.id or ""

        if btn_id == "btn_refresh":
            self._refresh_list()
        elif btn_id == "btn_open_folder":
            self._open_folder()
        elif btn_id.startswith("cfg_"):
            plugin_id = btn_id[4:]
            self._open_settings(plugin_id)

    def on_switch_changed(self, event: Switch.Changed) -> None:
        sw_id = event.switch.id or ""
        if sw_id.startswith("sw_"):
            plugin_id = sw_id[3:]
            loader = get_plugin_loader()

            if event.value:
                loader.enable_plugin(plugin_id)
                self.app.notify(self.app.t("plugin_enabled", name=plugin_id))
            else:
                loader.disable_plugin(plugin_id)
                self.app.notify(self.app.t("plugin_disabled", name=plugin_id))

            try:
                row = self.query_one(f"#row_{plugin_id}")
                lbl = row.query_one(".plugin-name", Static)
                meta = loader.get_plugin_meta(plugin_id)
                if meta:
                    status_symbol = "[green]✓[/]" if event.value else "[red]✗[/]"
                    lbl.update(f"{status_symbol}  {meta.name}")
            except Exception:

                self._refresh_list()

    async def _refresh_list(self):
        loader = get_plugin_loader()
        loader.discover_plugins()

        container = self.query_one("#plugins_container")
        await container.remove_children()
        for w in self._build_plugin_list():
            await container.mount(w)

        self.app.notify(self.app.t("plugin_list_refreshed"))

    def _open_folder(self):
        import subprocess
        import platform

        loader = get_plugin_loader()
        path = loader._plugins_dir

        try:
            if platform.system() == "Linux":
                subprocess.Popen(["xdg-open", path])
            elif platform.system() == "Darwin":
                subprocess.Popen(["open", path])
            else:
                subprocess.Popen(["explorer", path])
        except Exception as e:
            self.app.notify(self.app.t("plugin_folder_error", e=str(e)), severity="error")

    def _open_settings(self, plugin_id: str):
        from ui.dialogs import PluginSettingsDialog

        loader = get_plugin_loader()
        plugin = loader.get_plugin(plugin_id)

        if not plugin:
            plugin_class = loader._plugin_classes.get(plugin_id)
            if plugin_class:
                plugin = plugin_class()

                saved_settings = loader.get_plugin_settings(plugin_id)
                if saved_settings:
                    plugin.load_settings(saved_settings)

        if plugin and plugin.settings:

            current = loader.get_plugin_settings(plugin_id)
            self.app.push_screen(
                PluginSettingsDialog(plugin_id, plugin.meta, plugin.settings, current),
                self._on_settings_closed
            )

    def _on_settings_closed(self, result):
        if result:
            plugin_id, settings = result
            loader = get_plugin_loader()
            loader.save_plugin_settings(plugin_id, settings)
            self.app.notify(self.app.t("plugin_settings_saved"))

    def on_mount(self):
        loader = get_plugin_loader()
        loader.set_app(self.app)
        loader.discover_plugins()

