import { Route, Router } from "@solidjs/router";
import { listen } from "@tauri-apps/api/event";
import { createEffect, createSignal, onCleanup } from "solid-js";
import { Login } from "./Login";
import { ProtectedRoute } from "./ProtectedRoute";
import { Search } from "./Search";
import { Settings } from "./Settings";
import { ImageViewer } from "./components/ImageViewer";
import { ShareTarget } from "./components/share-target/ShareTarget";
import type { sendImage } from "./network";
import { ImageStatus } from "./components/image-status/ImageStatus";
import { invoke } from "@tauri-apps/api/core";

export const App = () => {
    const [processingImage, setProcessingImage] =
        createSignal<Awaited<ReturnType<typeof sendImage>>>();

    createEffect(() => {
        // TODO: Don't use window.location.href
        const unlisten = listen("focus-search", () => {
            window.location.href = "/";
        });

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

    // createEffect(() => {
    //     let listener: PluginListener;
    //     const setupListener = async () => {
    //         listener = await listenForShareEvents(
    //             async (intent: ShareEvent) => {
    //                 const contents = await readFile(intent.stream ?? "").catch(
    //                     (error: Error) => {
    //                         console.warn("fetching shared content failed:");
    //                         throw error;
    //                     },
    //                 );
    //                 setFile(
    //                     new File([contents], intent.name ?? "no-name", {
    //                         type: intent.content_type,
    //                     }),
    //                 );
    //                 setLogs((l) => [...l, intent.uri]);
    //             },
    //         );
    //     };
    //     setupListener();
    //     return () => {
    //         listener?.unregister();
    //     };
    // });

    const onTakeScreenshot = () => {
        invoke("take_screenshot");
    };

    return (
        <>
            <button type="button" onClick={onTakeScreenshot}>
                Take Screenshot [wayland :(]
            </button>
            <ImageViewer onSendImage={setProcessingImage} />
            <ImageStatus processingImage={processingImage} />
            <ShareTarget />
            <Router>
                <Route path="/login" component={Login} />

                <Route path="/" component={ProtectedRoute}>
                    <Route path="/" component={Search} />
                    <Route path="/settings" component={Settings} />
                </Route>
            </Router>
        </>
    );
};
