<script lang="ts">
    import { onMount } from "svelte"
    import { invoke } from "@tauri-apps/api/core"
    import { goto } from "@roxi/routify"

    import HDivider from "@/components/elements/HDivider.svelte"
    import Footer from "@/components/Footer.svelte"
    import {
        Button, Space, Text, Notification, Badge, Loader, Switch,
    } from "@svelteuidev/core"
    import { CrossCircled, ExternalLink, ReloadIcon } from "radix-icons-svelte"

    interface PluginEntry {
        name: string
        path: string
        enabled: boolean
        command_count: number
        error: string | null
    }

    let plugins: PluginEntry[] = []
    let loading = true
    let error = ""
    let info = ""
    let busy = ""

    async function load() {
        loading = true
        error = ""
        try {
            plugins = await invoke<PluginEntry[]>("plugins_list")
            plugins = [...plugins].sort((a, b) => a.name.localeCompare(b.name))
        } catch (e) {
            error = String(e)
        } finally {
            loading = false
        }
    }

    async function toggle(p: PluginEntry) {
        busy = p.name
        try {
            await invoke("plugins_set_enabled", { name: p.name, enabled: !p.enabled })
            await load()
            info = `«${p.name}» ${p.enabled ? "выключен" : "включён"}. Перезапусти Jarvis, чтобы применить.`
            setTimeout(() => { info = "" }, 5000)
        } catch (e) {
            error = String(e)
        } finally {
            busy = ""
        }
    }

    async function openFolder() {
        try {
            const path = await invoke<string>("plugins_open_folder")
            info = `Папка плагинов: ${path}`
            setTimeout(() => { info = "" }, 4000)
        } catch (e) {
            error = String(e)
        }
    }

    onMount(load)
</script>

<Space h="xl" />

<h2 class="page-title">Плагины</h2>
<Text size="sm" color="gray">
    Дополнительные voice-команды, которые лежат рядом с конфигом
    (<code>%APPDATA%\com.priler.jarvis\plugins\</code>). Каждый плагин — это
    папка с <code>command.toml</code> и Lua-скриптами.
    Меняется только после перезапуска.
</Text>

<Space h="md" />

<div class="actions-row">
    <Button color="lime" radius="md" size="sm" on:click={openFolder}>
        <ExternalLink size={14} /> &nbsp; Открыть папку
    </Button>
    &nbsp;
    <Button color="gray" radius="md" size="sm" on:click={load}>
        <ReloadIcon size={14} /> &nbsp; Обновить список
    </Button>
</div>

<Space h="md" />

{#if info}
    <Notification title="Готово" color="teal" on:close={() => { info = "" }}>
        {info}
    </Notification>
    <Space h="sm" />
{/if}

{#if error}
    <Notification
        title="Ошибка"
        icon={CrossCircled}
        color="red"
        on:close={() => { error = "" }}
    >
        {error}
    </Notification>
    <Space h="sm" />
{/if}

{#if loading}
    <Loader />
{:else if plugins.length === 0}
    <Text size="sm" color="gray">
        Плагинов пока нет. Скопируйте папку плагина в указанный каталог
        и нажмите «Обновить список».
    </Text>
{:else}
    <div class="plugin-list">
        {#each plugins as p}
            <div class="plugin-card" class:disabled={!p.enabled} class:errored={!!p.error}>
                <div class="plugin-header">
                    <span class="plugin-name">{p.name}</span>
                    {#if p.error}
                        <Badge color="red" variant="filled" size="sm">ошибка</Badge>
                    {:else}
                        <Badge color={p.enabled ? "lime" : "gray"} variant="filled" size="sm">
                            {p.command_count} команд
                        </Badge>
                    {/if}
                </div>
                <div class="plugin-path">{p.path}</div>
                {#if p.error}
                    <div class="plugin-error">{p.error}</div>
                {/if}
                <div class="plugin-actions">
                    <Switch
                        size="sm"
                        checked={p.enabled}
                        disabled={busy === p.name || !!p.error}
                        on:change={() => toggle(p)}
                    />
                    <Text size="xs" color={p.enabled ? "lime" : "gray"}>
                        {p.enabled ? "Включён" : "Выключен"}
                    </Text>
                </div>
            </div>
        {/each}
    </div>
{/if}

<Space h="xl" />

<Button color="gray" radius="md" size="sm" uppercase fullSize on:click={() => $goto("/")}>
    Назад
</Button>

<HDivider />
<Footer />

<style lang="scss">
    .page-title {
        margin: 0 0 4px 0;
        color: #fff;
        font-size: 1.3rem;
        font-weight: 600;
    }

    code {
        background: rgba(255, 255, 255, 0.08);
        padding: 1px 4px;
        border-radius: 3px;
        font-size: 0.8rem;
    }

    .actions-row {
        display: flex;
        gap: 0.5rem;
        align-items: center;
    }

    .plugin-list {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }

    .plugin-card {
        background: rgba(30, 40, 45, 0.75);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 10px;
        padding: 0.85rem 1rem;

        &.disabled {
            opacity: 0.55;
        }

        &.errored {
            border-color: rgba(220, 90, 90, 0.5);
        }
    }

    .plugin-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.35rem;
    }

    .plugin-name {
        font-size: 0.95rem;
        font-weight: 600;
        color: #fff;
    }

    .plugin-path {
        color: rgba(255, 255, 255, 0.4);
        font-size: 0.7rem;
        font-family: ui-monospace, "Cascadia Mono", monospace;
        word-break: break-all;
        margin-bottom: 0.5rem;
    }

    .plugin-error {
        color: rgba(255, 120, 120, 0.95);
        background: rgba(120, 30, 30, 0.25);
        font-size: 0.75rem;
        padding: 0.35rem 0.55rem;
        border-radius: 6px;
        margin-bottom: 0.5rem;
    }

    .plugin-actions {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
</style>
