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

export function FolderPicker() {
  const [selectedPath, setSelectedPath] = createSignal<string>("");
  const [status, setStatus] = 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,
        });
        setStatus(`Folder processed: ${response}`);
      }
    } catch (error) {
      setStatus(`Error: ${error}`);
    }
  };

  return (
    <div class="flex flex-col items-center gap-4">
      <button
        type="button"
        onClick={handleFolderSelect}
        class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
      >
        Select Folder
      </button>

      {selectedPath() && (
        <div class="text-left max-w-md">
          <p class="font-semibold">Selected folder:</p>
          <p class="text-sm break-all">{selectedPath()}</p>
        </div>
      )}

      {status() && <p class="text-sm text-gray-600">{status()}</p>}
    </div>
  );
}
