import { invoke } from "@tauri-apps/api/core";
import { createSignal, onMount } from "solid-js";

import { ShortcutItem } from "./ShortcutItem";
import { type Shortcut, useShortcutEditor } from "./hooks/useShortcutEditor";

export const Shortcuts = () => {
    const [shortcut, setShortcut] = createSignal<Shortcut>([]);

    async function getCurrentShortcut() {
        try {
            const res: string = await invoke("get_current_shortcut");
            console.log("DBG: ", res);
            setShortcut(res?.split("+"));
        } catch (err) {
            console.error("Failed to fetch shortcut:", err);
        }
    }

    onMount(() => {
        getCurrentShortcut();
    });

    const changeShortcut = (key: Shortcut) => {
        setShortcut(key);
        if (key.length === 0) return;
        invoke("change_shortcut", { key: key?.join("+") }).catch((err) => {
            console.error("Failed to save hotkey:", err);
        });
    };

    const {
        isEditing,
        currentKeys,
        startEditing,
        saveShortcut,
        cancelEditing,
    } = useShortcutEditor(shortcut(), changeShortcut);

    const onEditShortcut = async () => {
        startEditing();
        invoke("unregister_shortcut").catch((err) => {
            console.error("Failed to save hotkey:", err);
        });
    };

    const onCancelShortcut = async () => {
        cancelEditing();
        invoke("change_shortcut", { key: shortcut()?.join("+") }).catch(
            (err) => {
                console.error("Failed to save hotkey:", err);
            },
        );
    };

    const onSaveShortcut = async () => {
        saveShortcut();
    };

    return (
        <div class="flex flex-col gap-2 mt-4">
            <p class="text-sm text-neutral-700">
                Set up a to quickly open Haystack search. This shortcut also
                reloads items when updates happen (we should definetely fix
                that)
            </p>
            <ShortcutItem
                shortcut={shortcut()}
                isEditing={isEditing()}
                currentKeys={currentKeys()}
                onEdit={onEditShortcut}
                onSave={onSaveShortcut}
                onCancel={onCancelShortcut}
            />
        </div>
    );
};
