import { Button } from "@kobalte/core/button";
import { IconRefresh, IconSearch, IconSettings } from "@tabler/icons-solidjs";
import { listen } from "@tauri-apps/api/event";
import Fuse from "fuse.js";
import {
    For,
    Show,
    createEffect,
    createSignal,
    onCleanup,
    onMount,
} from "solid-js";
import { SearchCard } from "./components/search-card/SearchCard";
import { invoke } from "@tauri-apps/api/core";
import type { Shortcut } from "./components/shortcuts/hooks/useShortcutEditor";
import { base, type UserImage } from "./network";
import { useSearchImageContext } from "./contexts/SearchImageContext";
import { A } from "@solidjs/router";
import { useSetEntity } from "./WithEntityDialog";

export const Search = () => {
    const [searchResults, setSearchResults] = createSignal<UserImage[]>([]);
    const [searchQuery, setSearchQuery] = createSignal("");
    const setEntity = useSetEntity();

    const { images, imagesWithProperties, onRefetchImages } =
        useSearchImageContext();

    let fuze = new Fuse<UserImage>(images(), {
        keys: [
            { name: "rawData", weight: 1 },
            { name: "title", weight: 1 },
        ],
        threshold: 0.4,
    });

    createEffect(() => {
        setSearchResults(images());

        fuze = new Fuse<UserImage>(images(), {
            keys: [
                { name: "data.Name", weight: 2 },
                { name: "rawData", weight: 1 },
            ],
            threshold: 0.6,
        });
    });

    const onInputChange = (event: InputEvent) => {
        const query = (event.target as HTMLInputElement).value;

        if (query.length === 0) {
            setSearchResults(images());
        } else {
            setSearchQuery(query);
            setSearchResults(fuze.search(query).map((s) => s.item));
        }
    };

    let searchInputRef: HTMLInputElement | undefined;

    onMount(() => {
        if (searchInputRef) {
            searchInputRef.focus();
        }
    });

    createEffect(() => {
        // Listen for the focus-search event from Tauri
        const unlisten = listen("focus-search", () => {
            if (searchInputRef) {
                searchInputRef.focus();
            }
        });

        onCleanup(() => {
            unlisten.then((fn) => fn());
        });
    });

    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();
    });

    return (
        <>
            <main class="container pt-2">
                <div class="px-4 flex items-center">
                    <div class="inline-flex justify-between w-full rounded-xl text-base leading-none outline-none bg-white border border-neutral-200 text-neutral-900">
                        <div class="appearance-none inline-flex justify-center items-center w-auto outline-none rounded-md px-2.5 text-gray-900">
                            <IconSearch
                                size={20}
                                class="m-auto size-5 text-neutral-600"
                            />
                        </div>
                        <input
                            ref={searchInputRef}
                            type="text"
                            value={searchQuery()}
                            onInput={onInputChange}
                            placeholder="Search for stuff..."
                            autofocus
                            class="appearance-none inline-flex w-full min-h-[40px] text-base bg-transparent rounded-l-md outline-none placeholder:text-gray-600"
                        />
                    </div>
                    <Button
                        class="ml-2 p-2.5 bg-neutral-200 rounded-lg"
                        onClick={onRefetchImages}
                    >
                        <IconRefresh size={20} />
                    </Button>
                    <Button
                        as="a"
                        href="/settings"
                        class="ml-2 p-2.5 bg-neutral-200 rounded-lg"
                    >
                        <IconSettings size={20} />
                    </Button>
                </div>

                <div class="px-4 mt-4 bg-white rounded-t-2xl">
                    <div class="mt-4 overflow-scroll scrollbar-hide">
                        <Show
                            when={searchResults().length > 0}
                            fallback={
                                <div class="text-center text-lg m-auto mt-6 text-neutral-700">
                                    No results found
                                </div>
                            }
                        >
                            <div class="w-full grid grid-cols-9 gap-2 grid-flow-row-dense py-4">
                                <For each={searchResults()}>
                                    {(item) => (
                                        <div
                                            onClick={() => setEntity(item)}
                                            onKeyDown={(e) => {
                                                if (e.key === "Enter") {
                                                    setEntity(item);
                                                }
                                            }}
                                            class="h-[144px] border relative col-span-3 border-neutral-200 cursor-pointer overflow-hidden rounded-xl"
                                        >
                                            <span class="sr-only">
                                                {item.data.Name}
                                            </span>
                                            <SearchCard item={item} />
                                        </div>
                                    )}
                                </For>
                            </div>
                        </Show>
                    </div>
                </div>

                <div class="w-full grid grid-cols-9 gap-2 grid-flow-row-dense py-4">
                    <For each={Object.keys(imagesWithProperties())}>
                        {(imageId) => (
                            <A href={`/image/${imageId}`}>
                                <img
                                    alt="One of the users images"
                                    src={`${base}/image/${imageId}`}
                                />
                            </A>
                        )}
                    </For>
                </div>

                <div class="w-full border-t h-10 bg-white px-4 flex items-center border-neutral-100">
                    <p class="text-sm text-neutral-700">
                        Use{" "}
                        {shortcut().length > 0
                            ? shortcut().join("+")
                            : "shortcut"}{" "}
                        globally to toggle and reload this window
                    </p>
                </div>
            </main>
        </>
    );
};
