// TreasureForm.tsx
// Form for adding a new treasure to a session.
import { useState } from "react";
import type { CampaignId, Treasure } from "@/lib/types";
import { pb } from "@/lib/pocketbase";

/**
 * Renders a form to add a new treasure. Calls onCreate with the new treasure document.
 */
export const TreasureForm = ({
  campaign,
  onCreate,
}: {
  campaign: CampaignId;
  onCreate: (treasure: Treasure) => Promise<void>;
}) => {
  const [newTreasure, setNewTreasure] = useState("");
  const [adding, setAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!newTreasure.trim()) return;
    setAdding(true);
    setError(null);
    try {
      const treasureDoc: Treasure = await pb.collection("documents").create({
        campaign,
        data: {
          treasure: {
            text: newTreasure,
            discovered: false,
          },
        },
      });
      setNewTreasure("");
      await onCreate(treasureDoc);
    } catch (e: any) {
      setError(e?.message || "Failed to add treasure.");
    } finally {
      setAdding(false);
    }
  }

  return (
    <form
      className="flex flex-col items-center gap-2 mt-4 w-full"
      onSubmit={handleSubmit}
    >
      <div>
        <input
          type="text"
          className="flex-1 px-3 py-2 rounded bg-slate-800 text-slate-100 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500"
          placeholder="Add a new treasure..."
          value={newTreasure}
          onChange={(e) => setNewTreasure(e.target.value)}
          disabled={adding}
          aria-label="Add new treasure"
        />
      </div>
      {error && <div className="text-red-400 mt-2 text-sm">{error}</div>}
      <button
        type="submit"
        className="px-4 py-2 rounded bg-emerald-600 hover:bg-emerald-700 text-white font-semibold transition-colors disabled:opacity-60"
        disabled={adding || !newTreasure.trim()}
      >
        {adding ? "Adding..." : "Add Treasure"}
      </button>
    </form>
  );
};
