import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { createSignal } from "solid-js";

export function FolderPicker() {
    const [selectedPath, setSelectedPath] = createSignal<string>("");

    const handleFolderSelect = async () => {
        try {
            const selected = await open({
                directory: true,
                multiple: false,
            });

            if (selected) {
                setSelectedPath(selected as string);
                // Send the path to Rust
                const response = await invoke("handle_selected_folder", {
                    path: selected,
                });

                console.log("DBG: ", response);
            }
        } catch (error) {
            console.error("DBG: ", error);
        }
    };

    return (
        <div class="flex flex-col items-start gap-2">
            <p class="text-sm text-neutral-700">
                Select the folder where your screenshots are stored. We'll watch
                this folder for any changes and process any new screenshots.
            </p>
            <div class="flex items-center gap-2">
                <button
                    type="button"
                    onClick={handleFolderSelect}
                    class="bg-neutral-100 border border-neutral-300 rounded-md px-2 py-1"
                >
                    Select folder
                </button>

                {selectedPath() && (
                    <div class="text-left max-w-md">
                        <p class="text-sm break-all">{selectedPath()}</p>
                    </div>
                )}
            </div>
        </div>
    );
}
