import { useState } from 'react'

/**
 * 
 * @returns A JSX element representing the app’s gesture page.
 */
export default function GesturePage() {

  const [tags, setTags] = useState(["hello","happy","meditate","winner","crazy", "affirmative", "once upon a time"])
  const [selectedTag, setSelectedTag] = useState("");

  async function getTags() {
    try {
      // You can optionally use a query parameter: `commands/gesture/tags/?count=<number>`.
      // This will yield a list of tags with that count.
      const res = await fetch("http://localhost:8000/robot/commands/gesture/tags/"); 
      if (!res.ok) throw new Error("Failed communicating with the backend.");
      const jsonRes = await res.json();
      setTags(jsonRes["available_gesture_tags"]);
    } catch (err) {
      console.error("Failed to fetch tags:", err);
    }
  }

  async function doGesture() {
    if (!selectedTag) {
      alert("Please select a gesture first.");
      return;
    }

    const gesture = { endpoint: "actuate/gesture/tag", data: selectedTag };

    try {
      const res = await fetch("http://localhost:8000/robot/command/gesture", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(gesture),
      });
      if (!res.ok) throw new Error("Failed communicating with the backend.");
      console.log(`Successfully sent gesture '${selectedTag}' to the backend.`);
    } catch (err) {
      console.error("Failed to send gesture command:", err);
    }
  }

  return (
    <div className="card p-4 space-y-4">
      <button onClick={getTags}>Get Tags</button>

      <select
        value={selectedTag}
        onChange={(e) => setSelectedTag(e.target.value)}
        disabled={tags.length === 0}
      >
        <option value="">
          {tags.length === 0 ? "No tags loaded yet" : "-- Select a gesture --"}
        </option>
        {tags.map((tag) => (
          <option key={tag} value={tag}>
            {tag}
          </option>
        ))}
      </select>

      <button onClick={doGesture}>Do Gesture</button>
    </div>
  );
}