import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { Chat } from "./components/Chat";
import "./App.css";

function App() {
  const [projectPath, setProjectPath] = useState<string | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  async function selectProject() {
    try {
      setErrorMsg(null);
      // Open native folder picker
      const selected = await open({
        directory: true,
        multiple: false,
      });

      if (selected === null) {
        // User cancelled selection
        return;
      }

      // Invoke backend command to verify and set state
      // Note: invoke argument names must match Rust function args
      const confirmedPath = await invoke<string>("open_project", {
        path: selected,
      });
      setProjectPath(confirmedPath);
    } catch (e) {
      console.error(e);
      setErrorMsg(
        typeof e === "string" ? e : "An error occurred opening the project.",
      );
    }
  }

  return (
    <main className="container">
      <h1>AI Code Assistant</h1>

      {!projectPath ? (
        <div className="selection-screen">
          <p>
            Please select a project folder to start the Story-Driven Spec
            Workflow.
          </p>
          <button onClick={selectProject}>Open Project Directory</button>
        </div>
      ) : (
        <div className="workspace">
          <div
            className="toolbar"
            style={{
              padding: "10px",
              background: "#f0f0f0",
              borderRadius: "4px",
              color: "#333",
            }}
          >
            <strong>Active Project:</strong> {projectPath}
          </div>
          <hr style={{ margin: "20px 0" }} />
          <Chat />
        </div>
      )}

      {errorMsg && (
        <div className="error-message" style={{ marginTop: "20px" }}>
          <p style={{ color: "red" }}>Error: {errorMsg}</p>
        </div>
      )}
    </main>
  );
}

export default App;
