import { useState } from "react";
import type { CampaignId, Monster } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { SingleLineInput } from "@/components/form/SingleLineInput";
import { useDocumentCache } from "@/context/document/hooks";

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

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

  return (
    <BaseForm
      title="Create new monster"
      isLoading={adding || !name.trim()}
      onSubmit={handleSubmit}
      error={error}
      content={
        <SingleLineInput
          value={name}
          onChange={setName}
          placeholder="Monster description"
        />
      }
    />
  );
};
