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

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

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

  return (
    <form className="flex items-center gap-2 mt-4" onSubmit={handleSubmit}>
      <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 secret..."
        value={newSecret}
        onChange={(e) => setNewSecret(e.target.value)}
        disabled={adding}
        aria-label="Add new secret"
      />
      {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 || !newSecret.trim()}
      >
        {adding ? "Adding..." : "Add Secret"}
      </button>
    </form>
  );
};
