import { Navigate, Route, Router } from "@solidjs/router";
import type { PluginListener } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { readFile } from "@tauri-apps/plugin-fs";
import { platform } from "@tauri-apps/plugin-os";
import {
    type Component,
    type ParentProps,
    createEffect,
    onCleanup,
} from "solid-js";
import {
    type ShareEvent,
    listenForShareEvents,
} from "tauri-plugin-sharetarget-api";
import { Login } from "./Login";
import { ProtectedRoute } from "./ProtectedRoute";
import { Search } from "./Search";
import { Settings } from "./Settings";
import { ImageViewer } from "./components/ImageViewer";
import { SearchImageContextProvider } from "./contexts/SearchImageContext";
import { sendImageFile } from "./network";
import { Image } from "./Image";
import { WithEntityDialog } from "./WithEntityDialog";

const currentPlatform = platform();
console.log("Current Platform: ", currentPlatform);

const AppWrapper: Component<ParentProps> = ({ children }) => {
    return <div class="flex w-full justify-center h-screen">{children}</div>;
};

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

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

    createEffect(() => {
        if (currentPlatform !== "android") {
            return;
        }

        let listener: PluginListener;

        const setupListener = async () => {
            console.log("Setting up listener");

            listener = await listenForShareEvents(
                async (intent: ShareEvent) => {
                    console.log(intent);
                    const contents = await readFile(intent.stream ?? "").catch(
                        (error: Error) => {
                            console.warn("fetching shared content failed:");
                            throw error;
                        },
                    );

                    const f = new File([contents], intent.name ?? "no-name", {
                        type: intent.content_type,
                    });

                    sendImageFile(f.name, f);
                },
            );
        };

        setupListener();
        return () => {
            listener?.unregister();
        };
    });

    return (
        <SearchImageContextProvider>
            <ImageViewer />
            <Router>
                <Route path="/" component={AppWrapper}>
                    <Route path="/login" component={Login} />

                    <Route path="/" component={ProtectedRoute}>
                        <Route path="/" component={WithEntityDialog}>
                            <Route path="/" component={Search} />
                            <Route path="/image/:imageId" component={Image} />
                        </Route>
                        <Route path="/settings" component={Settings} />
                    </Route>
                </Route>
                <Route
                    path="*"
                    component={() => {
                        return <Navigate href="/" />;
                    }}
                />
            </Router>
        </SearchImageContextProvider>
    );
};
