// SceneForm.tsx
// Form for adding a new scene to a session.
import { useState } from "react";
import type { CampaignId, Scene } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { MultiLineInput } from "@/components/form/MultiLineInput";
import { useDocumentCache } from "@/context/document/hooks";

/**
 * Renders a form to add a new scene. Calls onCreate with the new scene document.
 */
export const NewSceneForm = ({
  campaign,
  onCreate,
}: {
  campaign: CampaignId;
  onCreate: (scene: Scene) => Promise<void>;
}) => {
  const { dispatch } = useDocumentCache();
  const [text, setText] = useState("");
  const [adding, setAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!text.trim()) return;
    setAdding(true);
    setError(null);
    try {
      const sceneDoc: Scene = await pb.collection("documents").create({
        campaign,
        type: "scene",
        data: {
          text,
        },
      });
      setText("");
      dispatch({ type: "setDocument", doc: sceneDoc });
      await onCreate(sceneDoc);
    } catch (e: any) {
      setError(e?.message || "Failed to add scene.");
    } finally {
      setAdding(false);
    }
  }

  return (
    <BaseForm
      title="Create new scene"
      onSubmit={handleSubmit}
      error={error}
      buttonText={adding ? "Adding..." : "Create"}
      content={
        <>
          <MultiLineInput
            value={text}
            onChange={(v) => setText(v)}
            disabled={adding}
            placeholder="Scene description..."
            aria-label="Add new scene"
          />
        </>
      }
    />
  );
};
