// 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";
import { BaseForm } from "@/components/form/BaseForm";
import { SingleLineInput } from "@/components/form/SingleLineInput";

/**
 * 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,
        type: "secret",
        data: {
          text: newSecret,
          discovered: false,
        },
      });
      setNewSecret("");
      await onCreate(secretDoc);
    } catch (e: any) {
      setError(e?.message || "Failed to add secret.");
    } finally {
      setAdding(false);
    }
  }

  return (
    <BaseForm
      title="Create new secret"
      isLoading={adding || !newSecret.trim()}
      onSubmit={handleSubmit}
      error={error}
      content={
        <SingleLineInput
          value={newSecret}
          onChange={setNewSecret}
          placeholder="Secret description"
        />
      }
    />
  );
};
