<script lang="ts">
    import { onMount, onDestroy } 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,
    } from "@svelteuidev/core"
    import { Clock, TrashIcon, CrossCircled } from "radix-icons-svelte"

    interface ScheduledTaskInfo {
        id: string
        name: string
        schedule_human: string
        action_kind: string
        action_text: string | null
        last_fired: number | null
        enabled: boolean
        created_at: number
    }

    let tasks: ScheduledTaskInfo[] = []
    let loading = true
    let error = ""
    let poll: ReturnType<typeof setInterval> | null = null

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

    async function removeTask(id: string, label: string) {
        if (!confirm(`Удалить задачу "${label}"?`)) return
        try {
            await invoke("scheduler_remove", { id })
            await load()
        } catch (e) { error = String(e) }
    }

    async function clearAll() {
        if (!confirm("Удалить ВСЕ запланированные задачи?")) return
        try {
            const count = await invoke<number>("scheduler_clear")
            error = `Удалено ${count}`
            setTimeout(() => { if (error.startsWith("Удалено")) error = "" }, 2500)
            await load()
        } catch (e) { error = String(e) }
    }

    onMount(() => {
        load()
        poll = setInterval(load, 5000)
    })

    onDestroy(() => {
        if (poll !== null) clearInterval(poll)
    })

    function fmtDate(ts: number | null): string {
        if (!ts) return "—"
        return new Date(ts * 1000).toLocaleString()
    }

    function actionColor(kind: string): string {
        switch (kind) {
            case "speak": return "cyan"
            case "lua": return "violet"
            default: return "gray"
        }
    }
</script>

<Space h="xl" />

<h2 class="page-title">Расписание</h2>
<Text size="sm" color="gray">
    Запланированные задачи: напоминания, ежедневные брифинги, привычки.
    Тик каждые 30 секунд.
</Text>

<Space h="md" />

{#if error}
    <Notification
        title="Сообщение"
        icon={CrossCircled}
        color={error.startsWith("Удалено") ? "teal" : "red"}
        on:close={() => { error = "" }}
    >
        {error}
    </Notification>
    <Space h="sm" />
{/if}

{#if loading}
    <Loader />
{:else if tasks.length === 0}
    <Text size="sm" color="gray">
        Расписание пустое. Добавь задачу голосом:
        «напомни через 5 минут выключить кофеварку», «каждые 2 часа напоминай пить воду»,
        «каждый день в 9 утра делай брифинг», «напоминай отдыхать глазам».
    </Text>
{:else}
    <div class="task-list">
        {#each tasks as task}
            <div class="task-card">
                <div class="task-header">
                    <div class="task-title">
                        <span class="task-name">{task.name}</span>
                        <Badge color={actionColor(task.action_kind)} variant="outline" size="sm">
                            {task.action_kind}
                        </Badge>
                    </div>
                    <Badge color="orange" variant="filled" size="sm">
                        {task.schedule_human}
                    </Badge>
                </div>

                {#if task.action_text}
                    <div class="task-body">
                        {task.action_text}
                    </div>
                {/if}

                <div class="task-meta">
                    <small>ID: <code>{task.id}</code></small>
                    <small>Создано: {fmtDate(task.created_at)}</small>
                    <small>Последний запуск: {fmtDate(task.last_fired)}</small>
                </div>

                <div class="task-actions">
                    <Button
                        color="red" radius="md" size="xs" uppercase
                        on:click={() => removeTask(task.id, task.name)}
                    >
                        <TrashIcon size={14} /> &nbsp; Отменить
                    </Button>
                </div>
            </div>
        {/each}
    </div>

    <Space h="md" />
    <Button color="red" radius="md" size="sm" uppercase fullSize on:click={clearAll}>
        Очистить всё ({tasks.length})
    </Button>
{/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;
    }

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

    .task-card {
        background: rgba(30, 40, 45, 0.75);
        border: 1px solid rgba(255, 168, 60, 0.18);
        border-radius: 10px;
        padding: 0.85rem 1rem;
    }

    .task-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.5rem;
        gap: 0.5rem;
    }

    .task-title {
        display: flex;
        gap: 0.5rem;
        align-items: center;
    }

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

    .task-body {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 6px;
        padding: 0.4rem 0.6rem;
        margin-bottom: 0.5rem;
        color: rgba(255, 255, 255, 0.85);
        font-size: 0.85rem;
        line-height: 1.4em;
    }

    .task-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        color: rgba(255, 255, 255, 0.4);
        font-size: 0.7rem;
        margin-bottom: 0.5rem;

        code {
            background: rgba(255, 255, 255, 0.05);
            padding: 1px 5px;
            border-radius: 3px;
            font-size: 0.65rem;
            color: rgba(255, 255, 255, 0.6);
        }
    }

    .task-actions {
        display: flex;
        gap: 0.4rem;
    }
</style>
